详解iOS 裁剪圆形图像并显示(类似于微信头像)

2020-01-20 23:27:38于丽

ViewController.m文件


#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  // Do any additional setup after loading the view, typically from a nib.
}


- (void)didReceiveMemoryWarning {
  [super didReceiveMemoryWarning];
  // Dispose of any resources that can be recreated.
}


- (IBAction)btnPressed:(id)sender {

  if([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypePhotoLibrary]) {

    //首先判断是否支持照片库,这个方法中的参数要和_imagePickerController.sourceType的值保持一致

    //如果支持

    _imagePickerController = [[UIImagePickerController alloc]init];

    _imagePickerController.view.backgroundColor = [UIColor orangeColor];
    _imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    _imagePickerController.delegate = self;
    _imagePickerController.allowsEditing = YES; //该参数默认是NO,建议设置为YES,否则裁剪成圆形图片的方法将获取到的是椭圆形的图片,与你的预想大相径庭

    [self presentViewController:_imagePickerController animated:YES completion:nil];

  }


}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

  _ablumImageView.image = [UIImage circleOldImage:[info objectForKey:UIImagePickerControllerEditedImage] borderWidth:30.0f borderColor:[UIColor orangeColor]]; 
  //该方法中Info的Key值“UIImagePickerControllerEditedImage”表示的是选择裁剪后的图片,如果使用这个Key值,则_imagePickerController.allowsEditing的值需要设置为YES。

  //如果_imagePickerController.allowsEditing的值设置的NO,则这个Key的值应该设置为UIImagePickerControllerOriginalImage

  /*
  info中的Key的值有如下几个:

  NSString *const UIImagePickerControllerMediaType ;指定用户选择的媒体类型(文章最后进行扩展)
NSString *const UIImagePickerControllerOriginalImage ;原始图片
NSString *const UIImagePickerControllerEditedImage ;修改后的图片
NSString *const UIImagePickerControllerCropRect ;裁剪尺寸
NSString *const UIImagePickerControllerMediaURL ;媒体的URL
NSString *const UIImagePickerControllerReferenceURL ;原件的URL
NSString *const UIImagePickerControllerMediaMetadata;当来数据来源是照相机的时候这个值才有效

  */


  [self dismissViewControllerAnimated:YES completion:nil];

}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{


  [self dismissViewControllerAnimated:YES completion:nil];

}

@end

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持ASPKU。


注:相关教程知识阅读请移步到IOS开发频道。