Swift 中使用 UIColor 创建 UIImage 的方法
Swift 中使用 UIColor 创建 UIImage 的方法
在 Swift 中,可以使用以下代码使用 UIColor 创建 UIImage:
func image(with color: UIColor) -> UIImage {
let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
代码解析:
- 创建一个 1x1 的 CGRect 作为绘制区域。
- 使用
UIGraphicsBeginImageContext开始绘制图像。 - 获取当前的上下文
UIGraphicsGetCurrentContext()。 - 使用
setFillColor设置填充颜色为指定的 UIColor 的 CGColor。 - 使用
fill填充绘制区域。 - 使用
UIGraphicsGetImageFromCurrentImageContext()获取绘制的图像。 - 使用
UIGraphicsEndImageContext()结束绘制。 - 返回创建的 UIImage。
示例:
let myColor = UIColor.red
let myImage = image(with: myColor)
注意:
- 该方法创建了一个 1x1 像素的 UIImage,如果需要创建更大的图片,需要修改
rect的大小。 - 该方法需要在主线程中执行。
希望以上内容对您有所帮助。如果您有任何其他问题,请随时提出。
原文地址: http://www.cveoy.top/t/topic/qtV1 著作权归作者所有。请勿转载和采集!