I have an 4×4 transformation matrix that is converted to CATransform3D. I need to apply it a UIImage and save as a new image in Documents folder. Any transformations that I can apply to cgcontext inside UIGraphicsImageRenderer image method work only with affine transformations that doesn’t suit me.
For now I have stuck with following implementation
extension UIImage {
func transformed(by transform: CATransform3D) -> UIImage {
let containerView = UIView(frame: CGRect(origin: .zero, size: self.size))
let imageView = UIImageView(image: self)
imageView.layer.transform = transform
containerView.addSubview(imageView)
let boundingBox = containerView.bounds.applyCATransform3D(transform)
let newSize = boundingBox.size
containerView.frame = CGRect(origin: .zero, size: newSize)
let renderer = UIGraphicsImageRenderer(size: newSize)
let image = renderer.image { context in
containerView.drawHierarchy(in: containerView.frame, afterScreenUpdates: true)
}
return image
}
}
The method returns image inside white canvas (which equals to newSize), but it doesn’t save imageView.layer transformations.
Are there any native methods provided by Apple to achieve this or I have to use some 3rd party library like OpenCV to implement this?