2009-06-13 8 views
110

Me gustaría crear un UIImage 1x1 dinámicamente basado en un UIColor.¿Cómo crear un UIImage 1x1 coloreado en el iPhone dinámicamente?

Sospecho que esto se puede hacer rápidamente con Quartz2d, ​​y estoy estudiando minuciosamente la documentación tratando de comprender los fundamentos. Sin embargo, parece que hay muchas trampas potenciales: no identifica correctamente el número de bits y bytes por cosas, no especifica los indicadores correctos, no libera datos no utilizados, etc.

¿Cómo se puede hacer esto de forma segura con Quartz? 2d (u otra forma más simple)?

Respuesta

318

Puede utilizar CGContextSetFillColorWithColor y CGContextFillRect para esto:

Swift

extension UIImage { 
    class func image(with color: UIColor) -> UIImage { 
     let rect = CGRectMake(0.0, 0.0, 1.0, 1.0) 
     UIGraphicsBeginImageContext(rect.size) 
     let context = UIGraphicsGetCurrentContext() 

     CGContextSetFillColorWithColor(context, color.CGColor) 
     CGContextFillRect(context, rect) 

     let image = UIGraphicsGetImageFromCurrentImageContext() 
     UIGraphicsEndImageContext() 

     return image 
    } 
} 

Swift3

extension UIImage { 
    class func image(with color: UIColor) -> UIImage { 
     let rect = CGRect(origin: CGPoint(x: 0, y:0), size: CGSize(width: 1, height: 1)) 
     UIGraphicsBeginImageContext(rect.size) 
     let context = UIGraphicsGetCurrentContext()! 

     context.setFillColor(color.cgColor) 
     context.fill(rect) 

     let image = UIGraphicsGetImageFromCurrentImageContext() 
     UIGraphicsEndImageContext() 

     return image! 
    } 
} 

Objective-C

+ (UIImage *)imageWithColor:(UIColor *)color { 
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f); 
    UIGraphicsBeginImageContext(rect.size); 
    CGContextRef context = UIGraphicsGetCurrentContext(); 

    CGContextSetFillColorWithColor(context, [color CGColor]); 
    CGContextFillRect(context, rect); 

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 

    return image; 
} 
+19

Bonito :-) Yo recomendaría poner este método en una categoría como método de clase, luego se puede agregar a un proyecto simplemente, y se puede invocar usando una línea como '[UIImage imageWithColor: [UIColor redColor]]'. –

+7

En caso de que esté creando estas imágenes en un bucle o usando un tamaño mayor, una optimización sería usar un lienzo opaco solo si el color tiene alfa. De esta manera: 'const CGFloat alpha = CGColorGetAlpha (color.CGColor); const BOOL opaque = alpha == 1; UIGraphicsBeginImageContextWithOptions (tamaño, opaque, 0); ' – hpique

+0

proporcione la versión rápida – fnc12

-6

Bien, esto no será exactamente lo que quiere, pero este código dibujará una línea. Puedes adaptarlo para hacer un punto. O al menos obtener un poco de información de él.

Hacer que la imagen 1x1 parezca un poco rara. Los trazos recorren la línea, por lo que un tramo de ancho 1.0 a 0.5 debería funcionar. Solo juega.

- (void)drawLine{ 

UIGraphicsBeginImageContext(CGSizeMake(320,300)); 

CGContextRef ctx = UIGraphicsGetCurrentContext(); 

float x = 0; 
float xEnd = 320; 
float y = 300; 

CGContextClearRect(ctx, CGRectMake(5, 45, 320, 300)); 

CGContextSetGrayStrokeColor(ctx, 1.0, 1.0); 

CGContextSetLineWidth(ctx, 1); 
CGPoint line[2] = { CGPointMake(x,y), CGPointMake(xEnd, y) }; 

CGContextStrokeLineSegments(ctx, line, 2); 

UIImage *theImage=UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
} 
6

he utilizado muchas veces de respuesta de Matt Steven fabricados de una categoría para ello:

@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 
7

Aquí hay otra opción basada en el código de Matt Stephen. Crea una imagen de color sólido redimensionable para que puedas reutilizarla o cambiar su tamaño (por ejemplo, usarla como fondo).

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

Colóquelo en la categoría UIImage y cambie el prefijo.

Cuestiones relacionadas