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
35
36
37
38
39
40
41
/**
绘制图片

@param color 背景色
@param size 大小
@param text 文字
@param textAttributes 字体设置
@param isCircular 是否圆形
@return 图片
*/
+ (UIImage *)zd_imageWithColor:(UIColor *)color
size:(CGSize)size
text:(NSString *)text
textAttributes:(NSDictionary *)textAttributes
circular:(BOOL)isCircular
{
if (!color || size.width <= 0 || size.height <= 0) return nil;
CGRect rect = CGRectMake(0, 0, size.width, size.height);
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();

// circular
if (isCircular) {
CGPathRef path = CGPathCreateWithEllipseInRect(rect, NULL);
CGContextAddPath(context, path);
CGContextClip(context);
CGPathRelease(path);
}

// color
CGContextSetFillColorWithColor(context, color.CGColor);
CGContextFillRect(context, rect);

// text
CGSize textSize = [text sizeWithAttributes:textAttributes];
[text drawInRect:CGRectMake((size.width - textSize.width) / 2, (size.height - textSize.height) / 2, textSize.width, textSize.height) withAttributes:textAttributes];

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}

iOS 根据颜色和文字生成图片
http://example.com/2017/12/02/iOS-根据颜色和文字生成图片/
作者
guanzhendong
发布于
2017年12月2日
许可协议