微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

UIGraphicsImageRenderer 应用滤镜后镜像图像

如何解决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
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。