使用透视变换转换UIView为UIImage

3

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

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

@LeoDabus 同样的结果 - Anton Vodolazkyi
@LeoDabus UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0.0) photoImageView.layer.presentationLayer()!.renderInContext(UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext UIGraphicsEndImageContext() 无法帮助 - Anton Vodolazkyi
1个回答

2
你可以使用UIView的方法drawViewHierarchyInRect。它会在当前上下文中呈现完整视图层次结构的快照,就像在屏幕上看到的一样。
试试这样做:
UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0.0)
view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

@AntonVodolazkyi 我已经测试过了,它是可以工作的。你可能做错了什么。我会发布一个带有示例项目的链接。 - Leo Dabus
我会等待您的回复。 - Anton Vodolazkyi
我已经尝试了,但结果仍然一样,这是屏幕截图链接:link - Anton Vodolazkyi
你需要渲染视图。 - Leo Dabus
1
非常感谢!你节省了我很多时间! - Anton Vodolazkyi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接