1 #import <UIKit/UIKit.h>
2
3 @interface UIImage (NJ)
4 /**
5 * 生成头像
6 *
7 * @param icon 头像图片名称
8 * @param border 头像边框大小
9 * @param color 头像边框的颜色
10 *
11 * @return 生成好的头像
12 */
13 + (instancetype)imageWithIcon:(NSString *)icon border:(NSInteger)border color:(UIColor *)color;
14 @end
15
16
17 #import "UIImage+NJ.h"
18 @implementation UIImage (NJ)
19
20 + (instancetype)imageWithIcon:(NSString *)icon border:(NSInteger)border color:(UIColor *)color
21 {
22 // 0. 加载原有图片
23 UIImage *image = [UIImage imageNamed:icon];
24
25 // 1.创建图片上下文
26 CGFloat margin = border;
27 CGSize size = CGSizeMake(image.size.width + margin, image.size.height + margin);
28
29 // YES 不透明 NO 透明
30 UIGraphicsBeginImageContextWithOptions(size, NO, 0);
31 // 2.绘制大圆
32 CGContextRef ctx = UIGraphicsGetCurrentContext();
33 CGContextAddEllipseInRect(ctx, CGRectMake(0, 0, size.width, size.height));
34 [color set];
35 CGContextFillPath(ctx);
36
37 // 3.绘制小圆
38 CGFloat smallX = margin * 0.5;
39 CGFloat smallY = margin * 0.5;
40 CGFloat smallW = image.size.width;
41 CGFloat smallH = image.size.height;
42 CGContextAddEllipseInRect(ctx, CGRectMake(smallX, smallY, smallW, smallH));
43 // [[UIColor greenColor] set];
44 // CGContextFillPath(ctx);
45 // 4.指定可用范围, 可用范围的适用范围是在指定之后,也就说在在指定剪切的范围之前绘制的东西不受影响
46 CGContextClip(ctx);
47
48 // 5.绘图图片
49 [image drawInRect:CGRectMake(smallX, smallY, smallW, smallH)];
50
51 // 6.取出图片
52 UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
53
54 return newImage;
55
56 }
57 @end
![](https://images2015.cnblogs.com/blog/631693/201601/631693-20160123123610328-1489845188.png)