Libra Studio Log

開発に関することやゲーム、ガジェットなどについてつらつらと書き記しています

UIColorを指定してUIImageを返すメソッド

f:id:daihase:20190809100049p:plain

こんばんわ、daihaseです。

今日はUIColorを引数にあたえてそれをUIImageとして返してくれるメソッドを紹介します。

class func createColorImageFromUIColor(color: UIColor) -> UIImage {
        // 1x1のbitmapを作成
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContext(rect.size)
        guard let context = UIGraphicsGetCurrentContext() else { assertionFailure(); return UIImage() }
        // bitmapを塗りつぶし
        context.setFillColor(color.cgColor)
        context.fill(rect)
        // UIImageに変換
        guard let image: UIImage = UIGraphicsGetImageFromCurrentImageContext() else { assertionFailure(); return UIImage() }
        UIGraphicsEndImageContext()
        return image
    }

 

今日はここまで。

それでは良いSwiftライフを〜