图像颜色错误?

时间:2018-03-14 18:37:16

标签: ios swift image colors

我希望使用下面添加的代码在UIImage上生成这样的酷炫。 但似乎有一个与颜色相关的疯狂错误

所以我喜欢我的功能是使用给定的RGB值(在我的情况下为r:76, g:255, b:0以绿色外观)为图像绘制线条颜色:

img1

但我使用的代码只是为洋红色而不是绿色的图像颜色着色:

img2

请查看我的代码:

func colorImage(image: UIImage) -> UIImage {
    let color = RGBA32(red: 76, green: 255, blue: 0, alpha: 255)
    let img: CGImage = image.cgImage!
    let context = CGContext(data: nil, width: img.width, height: img.height, bitsPerComponent: 8, bytesPerRow: 4 * img.width, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
    context.draw(img, in: CGRect(x: 0, y: 0, width: img.width, height: img.height))
    let binaryData = context.data!.bindMemory(to: RGBA32.self, capacity: img.width * img.height)
    for y in stride(from: 0, through: img.height, by: 10) {
        for x in 0..<img.width {
            let pixel = (y*img.width) + x
            binaryData[pixel] = color
        }
    }
    let output = context.makeImage()!
    return UIImage(cgImage: output, scale: image.scale, orientation: image.imageOrientation)
}
struct RGBA32: Equatable {
    private var color: UInt32
    init(red: UInt8, green: UInt8, blue: UInt8, alpha: UInt8) {
        let red   = UInt32(red)
        let green = UInt32(green)
        let blue  = UInt32(blue)
        let alpha = UInt32(alpha)
        color = (red << 24) | (green << 16) | (blue << 8) | (alpha << 0)
    }
    static func ==(lhs: RGBA32, rhs: RGBA32) -> Bool {
        return lhs.color == rhs.color
    }
}

Tbh我绝对不知道为什么会出现这个问题 - 所以任何帮助如何解决这个问题都将非常感激。谢谢:)

1 个答案:

答案 0 :(得分:0)

RGBA是一个令人困惑的词。目前尚不清楚R是32位数据中的最高有效字节还是4字节存储区中的第一个字节。

但是你的bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue, R取得第一名,G,B,然后是Alpha。

UInt32的小端表示中,R表示最低有效字节。

试用此版本的RGBA

struct RGBA32: Equatable {
    private var color: (red: UInt8, green: UInt8, blue: UInt8, alpha: UInt8)
    init(red: UInt8, green: UInt8, blue: UInt8, alpha: UInt8) {
        color = (red: red, green: green, blue: blue, alpha: alpha)
    }
    static func ==(lhs: RGBA32, rhs: RGBA32) -> Bool {
        return lhs.color == rhs.color
    }
}

(Swift结构或元组的内存分配没有明确定义,但上面的代码按预期工作。)

相关问题