この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
Extension
今回は UIImage の Extension として実装します。
Objective-C で言えばカテゴリです。
サンプルコード
import UIKit
extension UIImage {
class func colorImage(color: UIColor, size: CGSize) -> UIImage {
UIGraphicsBeginImageContext(size)
let rect = CGRect(origin: CGPointZero, size: size)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextFillRect(context, rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
引数で指定した色・サイズの UIImage を返します。
使い方
// 緑色で、サイズが 100 x 100 の UIImage を作成する
let size = CGSize(width: 100, height: 100)
let colorImage = UIImage.colorImage(UIColor.greenColor(), size: size)
まとめ
レアケースだとは思いますが、もし単色の UIImage 使うことがあれば参考にしてみてください。