我在使用 CIFilter
时遇到问题,它在输出图像的上方和下方应用偏移/边框。可以在下面的示例中看到。
在这个例子中,我只是简单地获取一个 UIImage,应用 CIPixellate
,固定方向,然后在全屏 UIImageView
中以红色背景色显示该图像来演示问题(将背景颜色设置为默认颜色“clear”会产生白色偏移。以下是 UIImageView
的设置。
通过调试,我知道问题发生在应用CIFilter
时的某个地方,并且它与UIImageView无关,如果我只是传递不带过滤器的图像,则不会发生此问题。
作为引用,这是我用来对图像进行像素化的代码:
extension UIImage {
func pixellate(amount: Int) -> UIImage? {
let ciImage = CIImage(cgImage: self.cgImage!)
let filter = CIFilter(name: "CIPixellate")
filter?.setValue(ciImage, forKey: kCIInputImageKey)
filter?.setValue(amount, forKey: kCIInputScaleKey)
guard let outputImage = filter?.outputImage else { return nil }
var pixellatedImage: UIImage?
// Fix the orientation of the newly processed image
let context = CIContext()
if let cgimg = context.createCGImage(outputImage, from: outputImage.extent) {
let processedImage = UIImage(cgImage: cgimg)
let portraitImage = UIImage(cgImage: processedImage.cgImage!, scale: 1.0, orientation: UIImageOrientation.right)
pixellatedImage = portraitImage
}
return pixellatedImage
}
}
这里发生了什么?有什么办法可以防止这种情况发生吗?
最佳答案
许多图像过滤器必须将邻近像素纳入目标像素的计算中。当然,这会导致边缘出现问题。一种可能性是在边缘重复像素。苹果提供了一种便捷的方法来做到这一点: clampedToExtent
Calling this method ... creates an image of infinite extent by repeating pixel colors from the edges of the original image.
...
let ciImage = CIImage(cgImage: self.cgImage!).clampedToExtent()
关于ios - 在图像上运行 CIFilter 会在上方和下方产生不需要的偏移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49758676/