CIRadialGradient缩小图像尺寸

时间:2018-11-09 15:18:32

标签: ios swift xcode core-image

将CIRadialGradient应用于我的图像后,其宽度减小了约20%。

guard let image = bgImage.image, let cgimg = image.cgImage else {
    print("imageView doesn't have an image!")
    return
}
let coreImage = CIImage(cgImage:cgimg)

guard let radialMask = CIFilter(name:"CIRadialGradient") else {
    return
}

guard let maskedVariableBlur = CIFilter(name:"CIMaskedVariableBlur") else {
    print("CIMaskedVariableBlur does not exist")
    return 
}
maskedVariableBlur.setValue(coreImage, forKey: kCIInputImageKey)

maskedVariableBlur.setValue(radialMask.outputImage, forKey: "inputMask")
guard let selectivelyFocusedCIImage = maskedVariableBlur.outputImage else {
    print("Setting maskedVariableBlur failed")
    return
}


bgImage.image = UIImage(ciImage: selectivelyFocusedCIImage)

为明确起见,bgImageUIImageView

为什么会发生这种情况以及如何解决?

没有RadialMask:

enter image description here

使用RadialMask:

enter image description here

与之不同的是,在我的物理iPhone上,较小的图像向左对齐。

3 个答案:

答案 0 :(得分:2)

查找文档,它是应用于图像的蒙版: enter image description here

文档:CIRadialGradient

答案 1 :(得分:2)

我倾向于通过使用CIContext并创建特定大小的CGImage而不是简单地使用UIImage(ciImage:)来明确声明图像的大小。假设您的inputImage被称为coreGraphics,请尝试以下操作:

let ciCtx = CIContext()
let cgiig = ctx.createCGImage(selectivelyFocusedCIImage, from: coreImage.extent)
let uiImage = UIImage(cgImage: cgIMG!)

一些注意事项......

(1)我从要包装的应用程序中提取了此代码。这是未经测试的代码(包括强制展开),但是我正在做的事情的概念很可靠。

(2)您没有解释很多您想做的事情,但是当我看到一个名为selectivelyFocusedCIImage的变量时,我担心您可能试图以比其他方式更具交互性的方式使用CoreImage。 “只是”创建一个图像。如果要“近乎实时”的性能,请使用(GLKView(从iOS 12起不推荐使用)或MTKView(而不是UIImageView)渲染CIImage。后者仅使用CPU,而前两者则使用GPU。

(3)最后,对CIContexts发出警告-创建它们很昂贵!通常,您可以对其进行编码,以使应用程序中的所有内容只能共享一个上下文。

答案 2 :(得分:0)

不同的大小是由模糊滤镜的内核大小引起的:

模糊滤镜需要对每个像素周围的区域进行采样。由于没有超出图像边界的像素,因此Core Image将结果图像的extend减小内核大小(模糊半径)的一半,以表示这些像素没有足够的信息来进行适当的模糊处理。

但是,您可以告诉Core Image将边框像素视为在所有方向上都无限延伸,以便模糊滤镜即使在图像边缘也可以获得足够的信息。然后,您可以将结果裁剪回原始尺寸。

在您的代码中,只需更改以下两行:

maskedVariableBlur.setValue(coreImage.clampedToExtent(), forKey: kCIInputImageKey)

bgImage.image = UIImage(ciImage: selectivelyFocusedCIImage.cropped(to:coreImage.extend))
相关问题