IOS 将图片转化裁剪为圆形头像

将图片转化裁剪为圆形的头像

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
-(UIImage*) imageToHeadView:(UIImage*)image withParam:(CGFloat)inset{

//先获取大小
CGFloat lengthW = CGImageGetWidth(image.CGImage);
CGFloat lengthH = CGImageGetHeight(image.CGImage);
CGFloat cutSzie;
//判断长宽比,获得最大正方形裁剪值
if(lengthW>= lengthH){
cutSzie = lengthH;
}
else cutSzie = lengthW;
//执行裁剪(为正方形)
CGImageRef sourceImageRef = [image CGImage]; //将UIImage转换成CGImageRef
CGRect rect = CGRectMake(lengthW/2-cutSzie/2, lengthH/2 - cutSzie/2, cutSzie, cutSzie); //构建裁剪区
CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, rect); //按照给定的矩形区域进行剪裁
UIImage *newImage = [UIImage imageWithCGImage:newImageRef]; //将CGImageRef转换成UIImage
//取圆形
UIGraphicsBeginImageContextWithOptions(newImage.size, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor);
CGContextFillPath(context);
CGContextSetLineWidth(context, .5);
CGContextSetStrokeColorWithColor(context, [UIColor clearColor].CGColor);
CGRect newrect = CGRectMake(inset, inset, newImage.size.width - inset * 2.0f, newImage.size.height - inset * 2.0f);
CGContextAddEllipseInRect(context, newrect);
CGContextClip(context);

[newImage drawInRect:newrect];
CGContextAddEllipseInRect(context, newrect);
CGContextStrokePath(context);
UIImage *circleImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return circleImg;
}

调用:

1
2
UIImage *img = [UIImage imageNamed:@"edit_background1.jpg"];
img = [self imageToHeadView:img withParam:0]; //封装的方法,从中间裁剪为圆形,后面参数为偏移量
0%