Vous pouvez utiliser CGContextSetFillColorWithColor
et CGContextFillRect
pour cela:
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;
}
Nice :-) Je recommanderais de mettre cette méthode dans une catégorie en tant que méthode de classe, puis de l'ajouter simplement dans un projet et de l'appeler en utilisant une ligne comme [UIImage imageWithColor: [UIColor redColor]] '. –
Dans le cas où vous créez ces images dans une boucle ou en utilisant une taille plus grande, une optimisation serait d'utiliser une toile opaque seulement si la couleur a alpha. Comme ceci: 'const CGFloat alpha = CGColorGetAlpha (color.CGColor); const BOOL opaque = alpha == 1; UIGraphicsBeginImageContextWithOptions (size, opaque, 0); ' – hpique
veuillez fournir la version rapide – fnc12