// 方法:設(shè)置頭像樣式
-(void)setHeadPortrait{
// self.liveHidImage.layer.masksToBounds=YES;
/**
* 添加手勢:也就是當用戶點擊頭像了之后,對這個操作進行反應(yīng)
*/
//允許用戶交互
_liveHidImage.userInteractionEnabled = YES;
//初始化一個手勢
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self
action:@selector(alterHeadPortrait:)];
//給imageView添加手勢
[_liveHidImage addGestureRecognizer:singleTap];
}
// 方法:alterHeadPortrait
-(void)alterHeadPortrait:(UITapGestureRecognizer )gesture{
/*
* 彈出提示框
*/
//初始化提示框
UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
//按鈕:從相冊選擇,類型:UIAlertActionStyleDefault
[alert addAction:[UIAlertAction actionWithTitle:@"從相冊選擇" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//初始化UIImagePickerController
UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
//獲取方式1:通過相冊(呈現(xiàn)全部相冊),UIImagePickerControllerSourceTypePhotoLibrary
//獲取方式2,通過相機,UIImagePickerControllerSourceTypeCamera
//獲取方法3,通過相冊(呈現(xiàn)全部圖片),UIImagePickerControllerSourceTypeSavedPhotosAlbum
PickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//允許編輯,即放大裁剪
PickerImage.allowsEditing = YES;
//自代理
PickerImage.delegate = self;
//頁面跳轉(zhuǎn)
[self presentViewController:PickerImage animated:YES completion:nil];
}]];
//按鈕:拍照,類型:UIAlertActionStyleDefault
[alert addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
/**
其實和從相冊選擇一樣,只是獲取方式不同,前面是通過相冊,而現(xiàn)在,我們要通過相機的方式
*/
UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
//獲取方式:通過相機
PickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
PickerImage.allowsEditing = YES;
PickerImage.delegate = self;
[self presentViewController:PickerImage animated:YES completion:nil];
}]];
//按鈕:取消,類型:UIAlertActionStyleCancel
[alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
[self presentViewController:alert animated:YES completion:nil];
}
UIImagePickerControllerDelegate
//PickerImage完成后的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
//定義一個newPhoto,用來存放我們選擇的圖片。
UIImage *newPhoto = [info objectForKey:@"UIImagePickerControllerEditedImage"];
_liveHidImage.image = newPhoto;
[self dismissViewControllerAnimated:YES completion:nil];
}