UIGraphicsImageRenderer 应用滤镜后镜像图像

问题描述

我正在尝试对图像应用过滤器。 应用滤镜效果很好,但它会垂直镜像图像。

最下面一行图片在init之后调用filter函数。

顶部的主图像,按下底部的一个后应用过滤器

ciFilterCIFilter.sepiaTone()

func applyFilter(image: UIImage) -> UIImage? {
        let rect = CGRect(origin: CGPoint.zero,size: image.size)
        let renderer = UIGraphicsImageRenderer(bounds: rect)

        ciFilter.setValue(CIImage(image: image),forKey: kCIInputImageKey)
        
        let image = renderer.image { context in
            let ciContext = CIContext(cgContext: context.cgContext,options: nil)

            if let outputImage = ciFilter.outputImage {
                ciContext.draw(outputImage,in: rect,from: rect)
            }
        }

        return image
    }

应用过滤器两次后,新图像被放大。

这是一些截图。

Start

After applying the filter

After applying the filter the second time

解决方法

您不需要使用 UIGraphicsImageRenderer。 您可以直接从 CIContext 获取图像。

func applyFilter(image: UIImage) -> UIImage? {
        
        ciFilter.setValue(CIImage(image: image),forKey: kCIInputImageKey)
        
        guard let ciImage = ciFilter.outputImage else {
            return nil
        }
        let outputCGImage = CIContext().createCGImage(ciImage,from: ciImage.extent)
        
        guard let _ = outputCGImage else { return nil }
        let filteredImage = UIImage(cgImage: outputCGImage!,scale: image.scale,orientation: image.imageOrientation)
        
        return filteredImage
    }

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...