ios 自定义CIFilter - a CIColorCube -不更改UIImage [重复]

qojgxg4l  于 2023-04-22  发布在  iOS
关注(0)|答案(1)|浏览(105)

此问题已在此处有答案

Get CIColorCube Filter Working In Swift(2个答案)
23小时前关闭
我做了一个自定义的CIColorCube过滤器,将预定灰度的图像(均匀间隔,包括黑色和白色)转换为彩色图像,每个阴影转换为不同的色调。问题是-它要么不给予任何输出,要么返回图像完全不变。下面是过滤器的代码:

class GreyToColoutrsFilterMaker{
static let FilterHaver = GreyToColoutrsFilterMaker()
let filter: CIFilter?
private init() {
    let size = Constants.SHADES_COUNT
    var cubeRGB = [Float]()
    for _ in 0 ..< size {
        for _ in 0 ..< size {
            for x in 0 ..< size {
                let red = CGFloat(x) / CGFloat(size-1)
                
                let hue = (1 - red) * 240 / 360
                let destColor = UIColor(hue: hue, saturation: 1, brightness: 1, alpha: 1)
                let colorParts = destColor.rgba
                cubeRGB.append(Float(colorParts.red))
                cubeRGB.append(Float(colorParts.green))
                cubeRGB.append(Float(colorParts.blue))
                cubeRGB.append(Float(colorParts.alpha))
            }
        }
    }
    let data = withUnsafeBytes(of: cubeRGB) { Data($0) }
    filter = CIFilter(name: "CIColorCube", parameters: ["inputCubeDimension": size, "inputCubeData": data])
}

下面是我如何在UIImage img上使用它:

if let filter = GreyToColoutrsFilterMaker.FilterHaver.filter{
            let ciImg = CIImage(image: img)
            filter.setDefaults()
            filter.setValue(ciImg, forKey: kCIInputImageKey)
            if let filteredImageData = filter.outputImage{
                let ciContext = CIContext(options: nil)
                if let filteredImageRef =   ciContext.createCGImage(filteredImageData, from: filteredImageData.extent){
                    img = UIImage(cgImage: filteredImageRef)
                }
            }
        }

如果删除了“filter.setDefaults()”行,则“if let filteredImageData = filter.outputImage”中的代码不会执行,这表明过滤器没有返回任何数据。但如果使用了该行,则过滤器不会以任何方式更改图像。

kzmpq1sx

kzmpq1sx1#

通过将数据初始化更改为:

let data = cubeRGB.withUnsafeBufferPointer{ Data(buffer: $0) }

之后,过滤器开始工作,而无需设置默认值。

相关问题