string绘制image

应用场景:用户头像为空时根据后台返回字符串绘制图片

设置size
CGRect rect = CGRectMake(0, 0, size.width, size.height);
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
设置形状(圆形)
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;

你可能感兴趣的:(string绘制image)