rotationAndPerspectiveTransform

rotationAndPerspectiveTransform

我想将具有透视变换的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()

结果是我得到了正确的图像但没有视角

最佳答案

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

尝试这样:

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

10-08 09:07