1. 程式人生 > >【iOS】一個完整的簡單的呼叫系統相機和相簿設定頭像

【iOS】一個完整的簡單的呼叫系統相機和相簿設定頭像

1.Xcode8,iOS10的許可權設定(不設定會崩潰):

找到專案的info.plist檔案,右鍵open As,以Source Code的形式開啟,將以下程式碼新增進去:

相機許可權設定:

<key>NSCameraUsageDescription</key>
    <string>cameraDesciption</string>

相簿許可權設定:

<key>NSPhotoLibraryUsageDescription</key>
    <string>photoLibraryDesciption</string>

設定好之後,clean一下。

2.在程式碼中設定代理

@interface MineCtrl ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property(nonatomic,strong)UIImagePickerController *imagePicker;
@property(nonatomic,strong)UIImageView *headShot;

3.設定相關屬性
    _imagePicker = [[UIImagePickerController alloc]init];
    _imagePicker.delegate = self;
    _headShot = [[UIImageView alloc]init];
    NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/currentImage.png"];
    _headShot.frame = CGRectMake((SCREEN_WIDTH-80)/2, (SCREEN_HEIGHT/4-80)/2, 80, 80);
<pre name="code" class="objc">   //不設定contentMode,圖片會被壓扁
    _headShot.contentMode = UIViewContentModeScaleAspectFill;
    [_headShot setClipsToBounds:YES];
    //將選擇的圖片顯示出來
    _headShot.image = [UIImage imageWithContentsOfFile:filePath];
    _headShot.backgroundColor = [UIColor grayColor];
    _headShot.layer.masksToBounds = YES;
    _headShot.layer.cornerRadius = 40;
    _headShot.layer.borderColor = [[UIColor whiteColor]CGColor];

//新增點選手勢

UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(ClickHandle)];
    [tapGesture setNumberOfTapsRequired:1];
    [_headShot addGestureRecognizer:tapGesture];

4.設定相關操作:
#pragma mark - 獲取頭像
-(void)ClickHandle
{
    UIAlertController *AlertSelect = [UIAlertController alertControllerWithTitle:@"提示" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *camera = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:_imagePicker animated:YES completion:nil];
    }];
    UIAlertAction *photo = [UIAlertAction actionWithTitle:@"從手機相簿選擇" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            _imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:_imagePicker animated:YES completion:nil];
    }];
    UIAlertAction *cancelAction=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [AlertSelect addAction:camera];
    [AlertSelect addAction:photo];
    [AlertSelect addAction:cancelAction];
    
    [self presentViewController:AlertSelect animated:YES completion:nil];
    
    
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo
{
    
    _headShot.image=image;
<pre name="code" class="objc">//將照片存到媒體庫
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
    [self saveImage:image];
[self dismissViewControllerAnimated:YES completion:nil]; } 4.儲存圖片到沙盒
#pragma mark - 照片存到本地後的回撥
- (void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo{
    if (!error) {
        NSLog(@"儲存成功");
    } else {
        NSLog(@"儲存失敗:%@", error);
    }
}
#pragma mark - 儲存圖片
- (void) saveImage:(UIImage *)currentImage {
    //設定照片的品質
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.5);
    
    NSLog(@"%@",NSHomeDirectory());
    // 獲取沙盒目錄
    NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/currentImage.png"];
    // 將圖片寫入檔案
    [imageData writeToFile:filePath atomically:NO];    
}
6.最後的樣式,即使退出程式,圖片也不會消失。