È possibile utilizzare CGContextSetFillColorWithColor
e CGContextFillRect
per questo:
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;
}
fonte
2009-06-14 16:31:57
Bello :-) Suggerirei di inserire questo metodo in una categoria come metodo di classe, quindi può essere aggiunto semplicemente a un progetto e richiamato utilizzando una riga come '[UIImage imageWithColor: [UIColor redColor]]'. –
Nel caso in cui si stiano creando queste immagini in un loop o utilizzando una dimensione maggiore, un'ottimizzazione consiste nell'utilizzare una tela opaca solo se il colore è alfa. Così: 'const CGFloat alpha = CGColorGetAlpha (color.CGColor); const BOOL opaque = alpha == 1; UIGraphicsBeginImageContextWithOptions (size, opaque, 0); ' – hpique
si prega di fornire la versione rapida – fnc12