我正在尝试使用透视校正功能进行图像裁剪。 我已经成功使用CIFilter CIPerspectiveCorrection。
我的问题是:如何从原始图像到裁剪后的图像进行动画处理(带有校正)?
根据文档,iOS不支持 layer.filters
。
我在想也许CATransform3D
是最好的选择,但是我对转换和矩阵并不熟悉。
我正在寻找与CamScanner应用程序中的裁切相同的动画。
答案 0 :(得分:0)
找到了一种方法,但是有点蛮力。我要做的是创建从初始图像和最终图像插入的多个图像,然后添加一个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
的开销非常明显,尤其是在生成更多帧的情况下。
希望苹果将来会在iOS上支持layer.filters
。