iOS 通过标题生成圆形图标

+ (UIImage *)createIconWithTitle:(NSString *)title {
    int red = arc4random() % 255 + 1;
    int green = arc4random() % 255 + 1;
    int blue = arc4random() % 255 + 1;
    UIColor *randomColor = [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:1];
    
    return [self createIconWithTitle:title
                              titleColor:[UIColor whiteColor]
                               titleFont:[UIFont systemFontOfSize:16]
                                   size:CGSizeMake(34, 34)
                                   color:randomColor];
}

+ (UIImage *)createIconWithTitle:(NSString *)title
                              titleColor:(UIColor *)titleColor
                               titleFont:(UIFont *)titleFont
                                    size:(CGSize)size
                                   color:(UIColor *)color {
    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    // 画圆
    CGPathRef circlur = CGPathCreateWithEllipseInRect(rect, NULL);
    CGContextAddPath(context, circlur);
    CGContextClip(context);
    CGPathRelease(circlur);
    
    // 颜色
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);
    
    // 标题
    NSDictionary *titleAttributes = @{
                                      NSForegroundColorAttributeName:titleColor ?: [UIColor whiteColor],
                                      NSFontAttributeName:titleFont ?: [UIFont systemFontOfSize:25]
                                      };
    CGSize textSize = [title sizeWithAttributes:titleAttributes];
    CGRect textRect = CGRectMake((size.width - textSize.width) / 2, (size.height - textSize.height) / 2, textSize.width, textSize.height);
    [title drawInRect:textRect withAttributes:titleAttributes];
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容