iOS10以上の場合は下のように記述します。
let image = UIGraphicsImageRenderer(size: view.bounds.size).image { context in view.layer.render(in: context.cgContext) }
iOS9以下の場合
下のようにUIViewを拡張してUIImage生成メソッドを追加すればOK。
extension UIView { func toImage() -> UIImage? { UIGraphicsBeginImageContextWithOptions(self.frame.size, false, 0) guard let context = UIGraphicsGetCurrentContext() else { return nil } self.layer.render(in: context) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } }
下のようにお手軽にUIViewをUIImageに変換できます。
let view = UIView(frame: CGRectMake(0.0, 0.0, 10.0, 10.0)) let view.imageValue()
ちなみにObjective-cだと下の通り。
@interface UIView(Hoge) - (UIImage*)toImage; @end @implementation UIView(Hoge) - (UIImage*)toImage { UIGraphicsBeginImageContextWithOptions(self.size, NO, 0); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextTranslateCTM(context, 0, 0); [self.layer renderInContext:context]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } @end