我试图模糊图像的一部分:
extension UIImage {
func blur(rect: CGRect, radius: CGFloat) -> UIImage? {
let context = CIContext(options: nil)
let inputImage = CIImage(cgImage: self.cgImage!)
let filter = CIFilter(name: "CIGaussianBlur")
filter?.setValue(inputImage, forKey: kCIInputImageKey)
filter?.setValue(radius, forKey: kCIInputRadiusKey)
let outputImage = filter?.outputImage
if let outputImage = outputImage {
let cgImage = context.createCGImage(outputImage, from: rect)
if let cgImage = cgImage {
return UIImage(cgImage: cgImage)
}
}
return nil
}
}
用法:
guard let blurredImage = self.imageView.image?.blur(rect: self.blur.frame, radius: 2.0) else { fatalError("could not blur image") }
let img = UIImageView(image: blurredImage)
img.frame = self.blur.frame
self.view.addSubview(img)
然而,当应用程序启动时,图片的错误部分会变得模糊。下面是图像;底部的矩形应该会模糊后面的图像,而不是模糊其他部分。
最佳答案
看来你走对了路。有几件事需要解决。。。
可以通过将屏幕比例传递到方法并更新rect的原点和大小来调整比例
由于CoreGraphics和UIKit坐标系之间的转换,模糊部分的定位被关闭。为了解决这个问题,你只需要用你想要模糊的矩形的位置和高度减去窗口的高度(考虑到比例)
请检查下面的代码:
extension UIImage {
func blur(rect: CGRect, radius: CGFloat, scale: CGFloat) -> UIImage? {
if let cgImage = self.cgImage {
let inputImage = CIImage(cgImage: cgImage)
let context = CIContext(options: nil)
let filter = CIFilter(name: "CIGaussianBlur")
filter?.setValue(inputImage, forKey: kCIInputImageKey)
filter?.setValue(radius, forKey: kCIInputRadiusKey)
// Rect bounds need to be adjusted for based on Image's Scale and Container's Scale
// Y Position Needs to be Inverted because of UIKit <-> CoreGraphics Coordinate Systems
let newRect = CGRect(
x: rect.minX * scale,
y: ((((CGFloat(cgImage.height) / scale)) - rect.minY - rect.height) * scale),
width: rect.width * scale,
height: rect.height * scale
)
if let outputImage = filter?.outputImage,
let cgImage = context.createCGImage(outputImage, from: newRect) {
return UIImage(
cgImage: cgImage,
scale: scale,
orientation: imageOrientation
)
}
}
return nil
}
}
let blurredImage = self.imageView.image?.blur(rect: self.blur.frame, radius: 2.0, scale: UIScreen.main.scale)
关于ios - createCGImage(_:from :)没有使用正确的矩形,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49075536/