图片裁剪之圆形头像
把一張普通的圖片刻意裁剪成圓形,并給圓形圖片加上圓形邊框
代碼抽取為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 }效果圖:
轉載于:https://www.cnblogs.com/caofutao/p/4824692.html
總結
- 上一篇: Oracle常见操作汇总(转)
- 下一篇: Swift 结构体和类的最大区别