Anton  Vodolazkyi
Anton Vodolazkyi

Reputation: 43

Converting UIView with perspective transform to UIImage

I want to convert UIView with perspective transform to UIImage but I got image without transformation. How can I keep transformation?

I'm making perspective transform for UIView with following code:

    var rotationAndPerspectiveTransform = CATransform3DIdentity
    rotationAndPerspectiveTransform.m34 = 1.0 / -500
    rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 45.0 * CGFloat(M_PI) / 180.0, 1.0, 0.0, 0.0)
    rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 45.0 * CGFloat(M_PI) / 180.0, 0.0, 1.0, 0.0)
    self.photoImageView.layer.transform = rotationAndPerspectiveTransform

then converting UIView with perspective transform to UIImage:

    UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0.0)
    view.layer.renderInContext(UIGraphicsGetCurrentContext()!)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

And as a result I'm getting correct image but without perspective

Upvotes: 3

Views: 1278

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236360

You can use UIView method drawViewHierarchyInRect. It will render a snapshot of the complete view hierarchy as visible onscreen into the current context.

Try like this:

UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0.0)
view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

Upvotes: 2

Related Questions