动画 CIFilter CIPerspectiveCorrection

Animating CIFilter CIPerspectiveCorrection

我正在尝试使用透视校正进行图像裁剪功能。 我已经成功使用 CIFilter CIPerspectiveCorrection。

我的问题是:如何从原始图像到裁剪图像(经过校正)制作动画?

根据文档,

layer.filters 不支持 iOS。 我在想也许 CATransform3D 是要走的路,但我不熟悉变换和矩阵。

我正在寻找与 CamScanner 应用程序中的裁剪相同的动画。

找到了一种方法,但有点粗暴。我所做的是创建从初始图像和最终图像插值的多个图像,然后添加 CAKeyFrameAnimation.

let points: [CGFloat] = [0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0]
    for i in points {
        let TLx = originalQuad.topLeft.x + i * (cartesianScaledQuad.topLeft.x - originalQuad.topLeft.x)
        let TLy = originalQuad.topLeft.y + i * (cartesianScaledQuad.topLeft.y - originalQuad.topLeft.y)
        let TL = CGPoint(x: TLx, y: TLy)

        let TRx = originalQuad.topRight.x + i * (cartesianScaledQuad.topRight.x - originalQuad.topRight.x)
        let TRy = originalQuad.topRight.y + i * (cartesianScaledQuad.topRight.y - originalQuad.topRight.y)
        let TR = CGPoint(x: TRx, y: TRy)

        let BLx = originalQuad.bottomLeft.x + i * (cartesianScaledQuad.bottomLeft.x - originalQuad.bottomLeft.x)
        let BLy = originalQuad.bottomLeft.y + i * (cartesianScaledQuad.bottomLeft.y - originalQuad.bottomLeft.y)
        let BL = CGPoint(x: BLx, y: BLy)

        let BRx = originalQuad.bottomRight.x + i * (cartesianScaledQuad.bottomRight.x - originalQuad.bottomRight.x)
        let BRy = originalQuad.bottomRight.y + i * (cartesianScaledQuad.bottomRight.y - originalQuad.bottomRight.y)
        let BR = CGPoint(x: BRx, y: BRy)

        let filteredImage = ciImage.applyingFilter("CIPerspectiveCorrection", parameters: [
            "inputTopLeft": CIVector(cgPoint: BL),
            "inputTopRight": CIVector(cgPoint: BR),
            "inputBottomLeft": CIVector(cgPoint: TL),
            "inputBottomRight": CIVector(cgPoint: TR)
            ])

        if let image = CIContext(options: nil).createCGImage(filteredImage, from: filteredImage.extent) {
            images.append(image)
        }
    }

    let anim:CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "contents")
    anim.duration = 0.5
    anim.values = images
    anim.delegate = self

    imageView.layer.add(anim, forKey: "contents");
    imageView.layer.contents = images.last!

递增值有问题,所以我不得不对每个点进行硬编码。工作正常,看起来不错。尽管创建 CGImage 的开销很明显,尤其是在生成更多帧的情况下。

希望 Apple 将来在 iOS 上支持 layer.filters