将具有透视变换的 UIView 转换为 UIImage

Converting UIView with perspective transform to UIImage

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