使用透视变换将UIView转换为UIImage

时间:2016-04-20 21:58:02

标签: ios swift uiview uiimage core-animation

我想用透视变换将UIView转换为UIImage,但是我得到了没有变换的图像。我怎样才能继续转型?

我正在使用以下代码为UIView进行透视转换:

    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

然后将UIView转换为UIImage:

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

结果我得到了正确的图像,但没有透视

1 个答案:

答案 0 :(得分:1)

您可以使用UIView方法drawViewHierarchyInRect。它将整个视图层次结构的快照呈现为屏幕上可见的当前上下文。

试试这样:

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