UIViewをUIImageにするExtension

UIViewを直接動かすのではなく、ダミー的にUIImageViewを動かすというようなことがやりたかったので、 UIViewをUIImageに変換するExtensionを探しました。

extension UIView {
    
    func toImage() -> UIImage? {

        UIGraphicsBeginImageContextWithOptions(self.frame.size, false, 0)
        if let context = UIGraphicsGetCurrentContext() {
            CGContextTranslateCTM(context, -self.frame.origin.x, -self.frame.origin.y)
            self.layer.renderInContext(context)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return image
        }
        return nil
    }
}

これで何でも、UIImageに変換できる・・・・はず。