我想基于UIColor动态创建1x1 UIImage.
我怀疑使用Quartz2d可以很快做到这一点,我正在仔细阅读文档,试图掌握基本原理.然而,看起来有很多潜在的缺陷:没有正确识别每个事物的位数和字节数,没有指定正确的标志,没有释放未使用的数据,等等.
如何使用Quartz 2d(或其他更简单的方式)安全地完成此操作?
我想基于UIColor动态创建1x1 UIImage.
我怀疑使用Quartz2d可以很快做到这一点,我正在仔细阅读文档,试图掌握基本原理.然而,看起来有很多潜在的缺陷:没有正确识别每个事物的位数和字节数,没有指定正确的标志,没有释放未使用的数据,等等.
如何使用Quartz 2d(或其他更简单的方式)安全地完成此操作?
您可以使用CGContextSetFillColorWithColor
和CGContextFillRect
来执行以下操作:
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;
}