在Swift中用纯色创建UIImage [英] Create UIImage with solid color in Swift

查看:837
本文介绍了在Swift中用纯色创建UIImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以编程方式创建一个由纯色填充的UIImage。任何人都知道如何在Swift中执行此操作?

I want to programmatically create an UIImage filled by a solid color. Anyone have an idea of how to do this in Swift?

推荐答案

另一个不错的解决方案, Swift 2.2 兼容,就是在UIImage中创建另一个构造函数,这样:

Another nice solution, Swift 2.2 compatible, is to create another constructor in UIImage, in this way:

public extension UIImage {
    public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
        let rect = CGRect(origin: .zero, size: size)
        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
        color.setFill()
        UIRectFill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        guard let cgImage = image?.CGImage else { return nil }
        self.init(CGImage: cgImage)
    }  
}

这样你可以用这种方式创建自定义彩色图像:

In this way you can create the custom colored-image in this way:

let redImage = UIImage(color: .redColor())

或者,可选择使用自定义尺寸创建图像:

Or, optionally, create the image with a custom size:

let redImage200x200 = UIImage(color: .redColor(), size: CGSize(width: 200, height: 200))

Swift 3.0

public extension UIImage {
  public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
    let rect = CGRect(origin: .zero, size: size)
    UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
    color.setFill()
    UIRectFill(rect)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    guard let cgImage = image?.cgImage else { return nil }
    self.init(cgImage: cgImage)
  }
}

这篇关于在Swift中用纯色创建UIImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆