MST
星途 面试题库

面试题:Objective-C中Camera拍摄照片并处理的复杂逻辑实现

假设你正在开发一个应用,用户通过Camera拍摄照片后,需要对照片进行旋转、裁剪等操作,然后保存到Photo Library中。请用Objective-C代码示例说明如何实现Camera的调用,以及完成上述照片处理和保存的功能,要求代码逻辑清晰,考虑到可能出现的错误处理。
50.4万 热度难度
编程语言Objective-C

知识考点

AI 面试

面试题答案

一键面试
  1. 导入必要的框架: 首先,在项目中导入 AVFoundationPhotos 框架,用于相机调用和照片保存。
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>
  1. 调用相机: 在视图控制器中定义相关属性,并实现调用相机的方法。
@interface ViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) UIImagePickerController *imagePicker;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIButton *captureButton = [UIButton buttonWithType:UIButtonTypeSystem];
    captureButton.frame = CGRectMake(100, 100, 200, 50);
    [captureButton setTitle:@"拍摄照片" forState:UIControlStateNormal];
    [captureButton addTarget:self action:@selector(captureImage) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:captureButton];
}

- (void)captureImage {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        self.imagePicker = [[UIImagePickerController alloc] init];
        self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        self.imagePicker.delegate = self;
        [self presentViewController:self.imagePicker animated:YES completion:nil];
    } else {
        NSLog(@"设备不支持相机功能");
    }
}
  1. 处理拍摄的照片: 实现 UIImagePickerControllerDelegate 的代理方法,对拍摄的照片进行旋转、裁剪等操作。
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
    UIImage *originalImage = info[UIImagePickerControllerOriginalImage];
    // 示例:顺时针旋转90度
    UIImage *rotatedImage = [self rotateImage:originalImage byDegrees:90];
    // 示例:裁剪图片,这里假设裁剪为原图片的一半大小
    CGRect cropRect = CGRectMake(0, 0, originalImage.size.width / 2, originalImage.size.height / 2);
    UIImage *croppedImage = [self cropImage:rotatedImage withRect:cropRect];
    
    [self dismissViewControllerAnimated:YES completion:^{
        // 保存处理后的图片到相册
        [self saveImageToPhotoLibrary:croppedImage];
    }];
}

- (UIImage *)rotateImage:(UIImage *)image byDegrees:(CGFloat)degrees {
    CGFloat radians = degrees * M_PI / 180;
    CGAffineTransform transform = CGAffineTransformMakeRotation(radians);
    CGSize rotatedSize;
    rotatedSize.width = fabs(image.size.width * cos(radians)) + fabs(image.size.height * sin(radians));
    rotatedSize.height = fabs(image.size.height * cos(radians)) + fabs(image.size.width * sin(radians));
    UIGraphicsBeginImageContext(rotatedSize);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, rotatedSize.width / 2.0, rotatedSize.height / 2.0);
    CGContextRotateCTM(context, radians);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextDrawImage(context, CGRectMake(-image.size.width / 2, -image.size.height / 2, image.size.width, image.size.height), image.CGImage);
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

- (UIImage *)cropImage:(UIImage *)image withRect:(CGRect)rect {
    CGRect adjustedRect = CGRectMake(rect.origin.x * image.scale, rect.origin.y * image.scale, rect.size.width * image.scale, rect.size.height * image.scale);
    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], adjustedRect);
    UIImage *croppedImage = [UIImage imageWithCGImage:imageRef scale:image.scale orientation:image.imageOrientation];
    CGImageRelease(imageRef);
    return croppedImage;
}
  1. 保存图片到相册: 使用 Photos 框架将处理后的图片保存到相册。
- (void)saveImageToPhotoLibrary:(UIImage *)image {
    __block BOOL success = NO;
    if (@available(iOS 11.0, *)) {
        PHPhotoLibrary *library = [PHPhotoLibrary sharedPhotoLibrary];
        [library performChanges:^{
            PHAssetCreationRequest *creationRequest = [PHAssetCreationRequest creationRequestForAssetFromImage:image];
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            if (success) {
                NSLog(@"图片保存成功");
            } else {
                NSLog(@"图片保存失败: %@", error);
            }
        }];
    } else {
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    if (error) {
        NSLog(@"图片保存失败: %@", error);
    } else {
        NSLog(@"图片保存成功");
    }
}

这样就完成了相机调用、照片处理以及保存到相册的功能,在实现过程中考虑了设备是否支持相机功能以及图片保存可能出现的错误。