//选择图片
- (IBAction)quxiangpian:(id)sender {
UIActionSheet *action = [[UIActionSheet alloc] initWithTitle:@"取图" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"从相册中取图" otherButtonTitles:@"拍照", nil];
[action showInView:self.view];
}
//相片来源 照相机或者相册
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
switch (buttonIndex) {
case 0:
[self pickImageFromAlbum];
break;
case 1:
[self pickImageFromCamera];
break;
default:
break;
}
}
//从相册取
- (void)pickImageFromAlbum
{
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
UIImagePickerController *imagepicker = [[UIImagePickerController alloc] init];
imagepicker.delegate = self;
imagepicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagepicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
imagepicker.allowsEditing = YES;
[self presentViewController:imagepicker animated:YES completion:nil];
}
}
//从照相取
- (void)pickImageFromCamera
{
//检查是否有相机
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
UIImagePickerController *imagepicker = [[UIImagePickerController alloc] init];
imagepicker.delegate = self;
imagepicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagepicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
imagepicker.allowsEditing = YES;
[self presentViewController:imagepicker animated:YES completion:nil];
}
}
//显示图片
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
[picker dismissViewControllerAnimated:YES completion:nil];
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
self.imageView.image = image;
}
但是返回的图像并不是正方形,显示在用户头像的View里面产生明显的拉伸。研究了很久各种裁剪算法,甚至想创建一个view来处理。突然发现代码中从相机、相册获取图片时采用的的
UIImagePickerControllerOriginalImage
于是跟踪进去一看:
UIKIT_EXTERN NSString *const UIImagePickerControllerMediaType; // an NSString (UTI, i.e. kUTTypeImage)
UIKIT_EXTERN NSString *const UIImagePickerControllerOriginalImage; // a UIImage
UIKIT_EXTERN NSString *const UIImagePickerControllerEditedImage; // a UIImage
UIKIT_EXTERN NSString *const UIImagePickerControllerCropRect; // an NSValue (CGRect)
UIKIT_EXTERN NSString *const UIImagePickerControllerMediaURL; // an NSURL
UIKIT_EXTERN NSString *const UIImagePickerControllerReferenceURL NS_AVAILABLE_IOS(4_1); // an NSURL that references an
恍然大悟,很简单,用UIImagePickerControllerEditedImage,万事搞定。