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;
}

你可能感兴趣的:(iOS 通过标题生成圆形图标)