把一张普通的图片刻意裁剪成圆形,并给圆形图片加上圆形边框
代码抽取为UIImage的分类方法,如下:
1 + (instancetype)circleImageWithName:(NSString *)name borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor 2 { 3 // 1.加载原图 4 UIImage *oldImage = [UIImage imageNamed:name]; 5 6 // 2.开启上下文 7 CGFloat imageW = oldImage.size.width + 2 * borderWidth; 8 CGFloat imageH = oldImage.size.height + 2 * borderWidth; 9 CGSize imageSize = CGSizeMake(imageW, imageH); 10 UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0); 11 12 // 3.取得当前的上下文 13 CGContextRef ctx = UIGraphicsGetCurrentContext(); 14 15 // 4.画边框(大圆) 16 [borderColor set]; 17 CGFloat bigRadius = imageW * 0.5; // 大圆半径 18 CGFloat centerX = bigRadius; // 圆心 19 CGFloat centerY = bigRadius; 20 CGContextAddArc(ctx, centerX, centerY, bigRadius, 0, M_PI * 2, 0); 21 CGContextFillPath(ctx); // 画圆 22 23 // 5.小圆 24 CGFloat smallRadius = bigRadius - borderWidth; 25 CGContextAddArc(ctx, centerX, centerY, smallRadius, 0, M_PI * 2, 0); 26 // 裁剪(后面画的东西才会受裁剪的影响) 27 CGContextClip(ctx); 28 29 // 6.画图 30 [oldImage drawInRect:CGRectMake(borderWidth, borderWidth, oldImage.size.width, oldImage.size.height)]; 31 32 // 7.取图 33 UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); 34 35 // 8.结束上下文 36 UIGraphicsEndImageContext(); 37 38 return newImage; 39 }
效果图:
时间: 2024-10-06 10:44:50