裁切出一张圆形的头像图片
效果图
步骤:
// 0.加载原图
UIImage *oldImage = [UIImageimageNamed:@"me"];
// 1.取得图片的上下文
CGFloat borderW = 2; //圆环的宽度
CGFloat imageW = oldImage.size.width +borderW *2;
CGFloat imageH = oldImage.size.height +borderW *2;
CGSize imageSize = CGSizeMake(imageW, imageH);
UIGraphicsBeginImageContextWithOptions(imageSize,NO, 0.0);
// 2.获取上下文对象
CGContextRef ctr = UIGraphicsGetCurrentContext();
// 3.画一个大圆
[[UIColor whiteColor] set]; // 给大圆设置白色背景
CGFloat bigRadius = imageW *0.5; // 大圆半径
CGFloat bigX = bigRadius; // 圆心
CGFloat bigY = bigRadius;
CGContextAddArc(ctr, bigX, bigY, bigRadius,0, M_PI * 2, 0);
CGContextFillPath(ctr); // 画圆这句话才将圆画到屏幕上
// 4.画一个小圆
// [[UIColor blackColor] set];
CGFloat smallRadius = bigRadius - borderW;
CGContextAddArc(ctr, bigRadius, bigRadius, smallRadius,0, M_PI * 2, 0);
// CGContextFillPath(ctr); // 只是用来测试显示的小圆
// 5.裁切 (裁切完之后的路径影响到后面的图片显示)
CGContextClip(ctr);
// 6.画图
[oldImage drawInRect:CGRectMake(borderW, borderW, oldImage.size.width,oldImage.size.height)];
// 7.获取图片
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
// 8.结束
UIGraphicsEndImageContext();
// 9.显示
self.iconView.image = newImage;
// 10.写入文件
NSData *data = UIImagePNGRepresentation(newImage);
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"new.png"];
[data writeToFile:path atomically:YES];