裁剪圆形头像

裁剪圆形头像_第1张图片
circlePhoto1.png

裁剪圆形头像###

//裁剪圆形头像
-(void)clipRoundPhoto{
    //打开图片上下文
    UIImage *image = [UIImage imageNamed:@"阿狸头像"];
    UIGraphicsBeginImageContextWithOptions(image.size, NO, 1);
    
    //设置裁剪区域
    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
    [path addClip];
    
    //画图像
    [image drawAtPoint:CGPointZero];
    
    //导出图片
    UIImage * newimage = UIGraphicsGetImageFromCurrentImageContext();
    
    //显示到imageView
    self.imageView.image = newimage;
}
裁剪圆形头像_第2张图片
circlePhoto2.png

裁剪带边框的圆形头像###

ViewController.m文件

#import "UIImage+image.h"

- (void)viewDidLoad {
    [super viewDidLoad];
    self.imageView.image = [UIImage imageWithBorder:15 borderColor:[UIColor colorWithRed:1.0 green:0.8 blue:0.0 alpha:1.0] image:[UIImage imageNamed:@"阿狸头像"]];
}

UIImage+image.m 分类文件

+(instancetype)imageWithBorder:(CGFloat)borderWidth borderColor:(UIColor *)borderColor image:(UIImage *)image{
    //开启图片上下文
    CGSize size = CGSizeMake(image.size.width+borderWidth*2, image.size.height+borderWidth*2);
    UIGraphicsBeginImageContextWithOptions(size, NO, 1);
    
    //大圆背景
    UIBezierPath * bigCirclePath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, size.width, size.height)];
    [borderColor set];
    [bigCirclePath fill];
    
    //设置裁剪小圆路径
    UIBezierPath * smallCirclePath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(borderWidth, borderWidth, image.size.width, image.size.height)];
    [smallCirclePath addClip];
    
    //画图片
    [image drawAtPoint:CGPointMake(borderWidth, borderWidth)];
    
    //导出图片
    UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    //关闭图片上下文
    UIGraphicsEndImageContext();
    
    return newImage;
}

你可能感兴趣的:(裁剪圆形头像)