iOS設置用戶頭像(從相冊,圖庫或者拍照獲取)

iOS設置用戶頭像(從相冊,圖庫或者拍照獲取)

①初始化UIImagePickerController

self.imagePicker=[[UIImagePickerController alloc] init];

 ②遵守協議

@interface ViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>

 

//設置代理  
_imagePicker.delegate=self;

   //可編輯

   _imagePicker.allowsEditing=YES;

   //設置頭像圖片圓角

    _selectedRightImage.layer.cornerRadius=100;
    _selectedRightImage.layer.borderWidth=6;
    _selectedRightImage.layer.masksToBounds=YES;
    _selectedRightImage.layer.borderColor=[[UIColor whiteColor] CGColor];
    self.selectedRightImage.userInteractionEnabled=YES;

⑤給圖片添加點擊事件

UITapGestureRecognizer *tapPicture=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectedImageForIcon)];
    [_selectedRightImage addGestureRecognizer:tapPicture];

⑥從相冊,圖庫,相機獲取圖片

複製代碼
-(void)selectedImageForIcon
{

    UIAlertController *alertController=[UIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *actionCamera=[UIAlertAction actionWithTitle:@"打開相機" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        _imagePicker.sourceType=UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:_imagePicker animated:YES completion:nil];
        
    }];
    
    UIAlertAction *actionPhotoLIbrary=[UIAlertAction actionWithTitle:@"打開相冊" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        _imagePicker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:_imagePicker animated:YES completion:nil];
        
    }];
    
    UIAlertAction *actionPhotoAlbum=[UIAlertAction actionWithTitle:@"打開圖庫" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        _imagePicker.sourceType=UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        [self presentViewController:_imagePicker animated:YES completion:nil];
        
    }];
    
    UIAlertAction *cancelAction=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alertController addAction:actionCamera];
    
    [alertController addAction:actionPhotoAlbum];
    
    [alertController addAction:actionPhotoLIbrary];
    
    [alertController addAction:cancelAction];
    
    [self presentViewController:alertController animated:YES completion:nil];

}
複製代碼

 
實現這個方法就可以更換頭像了!!!

複製代碼
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo
{

_selectedRightImage.image=image;
[self dismissViewControllerAnimated:YES completion:nil];

}
複製代碼

 

最終效果圖:

 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章