Bạn có thể sử dụng CGContextSetFillColorWithColor
và CGContextFillRect
cho việc này:
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;
}
Nguồn
2009-06-14 16:31:57
Đẹp nhất :-) Tôi khuyên bạn nên đưa phương thức này vào một thể loại như một phương thức lớp, sau đó nó có thể được thêm vào một dự án đơn giản và được gọi bằng một dòng như '[UIImage imageWithColor: [UIColor redColor]]'. –
Trong trường hợp bạn đang tạo những hình ảnh này trong vòng lặp hoặc sử dụng kích thước lớn hơn, tối ưu hóa sẽ chỉ sử dụng canvas mờ nếu màu có alpha. Như thế này: 'const CGFloat alpha = CGColorGetAlpha (color.CGColor); const BOOL opaque = alpha == 1; UIGraphicsBeginImageContextWithOptions (kích thước, opaque, 0); ' – hpique
vui lòng cung cấp phiên bản swift – fnc12