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

后端 未结 6 2029
情书的邮戳
情书的邮戳 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:17

    I used Matt Steven's answer many times so made a category for it:

    @interface UIImage (mxcl)
    + (UIImage *)squareImageWithColor:(UIColor *)color dimension:(int)dimension;
    @end
    
    @implementation UIImage (mxcl)
    + (UIImage *)squareImageWithColor:(UIColor *)color dimension:(int)dimension {
        CGRect rect = CGRectMake(0, 0, dimension, dimension);
        UIGraphicsBeginImageContext(rect.size);
        CGContextRef context = UIGraphicsGetCurrentContext();
    
        CGContextSetFillColorWithColor(context, [color CGColor]);
        CGContextFillRect(context, rect);
    
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        return image;
    }
    @end
    

提交回复
热议问题