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

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

问题描述

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

解决方案

Another nice solution, Swift 3.0

    public extension UIImage {
      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 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 中创建纯色 UIImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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