How to create a colored 1x1 UIImage on the iPhone dynamically?

后端 未结 6 2030
情书的邮戳
情书的邮戳 2020-11-28 01:53

I would like to create a 1x1 UIImage dynamically based on a UIColor.

I suspect this can quickly be done with Quartz2d, and I\'m poring over the documentation trying

6条回答
  •  清酒与你
    2020-11-28 02:19

    Here's another option based on Matt Stephen's code. It creates a resizable solid color image such that you could reuse it or change it's size (e.g. use it for a background).

    + (UIImage *)prefix_resizeableImageWithColor:(UIColor *)color {
        CGRect rect = CGRectMake(0.0f, 0.0f, 3.0f, 3.0f);
        UIGraphicsBeginImageContext(rect.size);
        CGContextRef context = UIGraphicsGetCurrentContext();
    
        CGContextSetFillColorWithColor(context, [color CGColor]);
        CGContextFillRect(context, rect);
    
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        image = [image resizableImageWithCapInsets:UIEdgeInsetsMake(1, 1, 1, 1)];
    
        return image;
    }
    

    Put it in a UIImage category and change the prefix.

提交回复
热议问题