【问题标题】:UIGraphicsImageRenderer mirrors image after applying filterUIGraphicsImageRenderer 应用过滤器后镜像图像
【发布时间】:2021-06-27 04:07:46
【问题描述】:

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

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

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

ciFilter 是 CIFilter.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
    }

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

这里有一些截图。

【问题讨论】:

  • UIKit 原点在左上角,但 CIFilter 原点在左下角。你必须补偿。

标签: ios swift uiimage core-image uigraphicsimagerenderer


【解决方案1】:

您不需要使用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
    }

【讨论】:

  • 这可行,但使用的内存比 UIGraphicsImageRenderer 多。这就是为什么,我不想使用这种方法。
  • 在你的函数中你可以试试这个:return UIImage(cgImage: image.cgImage!, scale: image.scale,orientation: image.imageOrientation)
  • image.cgImage 和 image.ciImage 始终为零。我也试过了。
  • 你试过了吗:CIImage(image: image)?.cgImage
  • 我不知道为什么,但它仍然为零。但我有一个控制台输出:CGBitmapContextCreateWithCallbacks: failed to create CGAutomaticBitmapContextInfo.
猜你喜欢
  • 1970-01-01
  • 2015-06-17
  • 1970-01-01
  • 1970-01-01
  • 2021-12-04
  • 1970-01-01
  • 2021-04-08
  • 2016-12-29
  • 1970-01-01
相关资源
最近更新 更多