ios objective-c uibutton uiimage

ios - Crear un UIImage desde un UIColor para usar como imagen de fondo para UIButton



objective-c (7)

¿Estás usando ARC? El problema aquí es que no tiene una referencia al objeto UIColor que está intentando aplicar; el CGColor está respaldado por ese UIColor , pero ARC desasignará el UIColor antes de que tenga la oportunidad de usar el CGColor .

La solución más clara es tener una variable local que apunte a su UIColor con el atributo objc_precise_lifetime .

Puede leer más sobre este caso exacto en este artículo sobre UIColor y vidas útiles cortas de ARC u obtener más detalles sobre el atributo objc_precise_lifetime .

Esta pregunta ya tiene una respuesta aquí:

Estoy creando una imagen coloreada como esta:

CGRect rect = CGRectMake(0, 0, 1, 1); UIGraphicsBeginImageContext(rect.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [[UIColor redColor] CGColor]); // [[UIColor colorWithRed:222./255 green:227./255 blue: 229./255 alpha:1] CGColor]) ; CGContextFillRect(context, rect); UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();

y luego usarlo como imagen de fondo de un botón:

[resultButton setBackgroundImage:img forState:UIControlStateNormal];

Esto funciona muy bien con el color rojo, sin embargo, quiero usar un color RGB (como se muestra en la línea comentada). Cuando uso el color RGB, el fondo de los botones no cambia.

¿Qué me estoy perdiendo?


Agrega los puntos a todos los valores:

[[UIColor colorWithRed:222./255. green:227./255. blue: 229./255. alpha:1] CGColor]) ;

De lo contrario, está dividiendo float por int.


Creé una categoría alrededor de UIButton para poder establecer el color de fondo del botón y establecer el estado. Puede encontrar esto útil.

@implementation UIButton (ButtonMagic) - (void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state { [self setBackgroundImage:[UIButton imageFromColor:backgroundColor] forState:state]; } + (UIImage *)imageFromColor:(UIColor *)color { CGRect rect = CGRectMake(0, 0, 1, 1); UIGraphicsBeginImageContext(rect.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [color CGColor]); CGContextFillRect(context, rect); UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; }

Esto será parte de un conjunto de categorías de ayuda que estoy abriendo este mes.

Swift 2.2

extension UIImage { static func fromColor(color: UIColor) -> UIImage { let rect = CGRect(x: 0, y: 0, width: 1, height: 1) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() CGContextSetFillColorWithColor(context, color.CGColor) CGContextFillRect(context, rect) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img } }

Swift 3.0

extension UIImage { static func from(color: UIColor) -> UIImage { let rect = CGRect(x: 0, y: 0, width: 1, height: 1) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() context!.setFillColor(color.cgColor) context!.fill(rect) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img! } }

Usar como

let img = UIImage.from(color: .black)


Solución Xamarin.iOS

public UIImage CreateImageFromColor() { var imageSize = new CGSize(30, 30); var imageSizeRectF = new CGRect(0, 0, 30, 30); UIGraphics.BeginImageContextWithOptions(imageSize, false, 0); var context = UIGraphics.GetCurrentContext(); var red = new CGColor(255, 0, 0); context.SetFillColor(red); context.FillRect(imageSizeRectF); var image = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); return image; }


Supongo que 255 en 227./255 se percibe como un número entero y la división siempre es return 0


Tu código funciona bien Puede verificar los colores RGB con el xScope de Iconfactory . Simplemente compárelo con [UIColor whiteColor] .


CGContextSetFillColorWithColor(context,[[UIColor colorWithRed:(255/255.f) green:(0/255.f) blue: (0/255.f) alpha:1] CGColor]);