shixiaoz shixiaoz - 4 years ago 161
Swift Question

Create an image from raw pixels, but color is not able to displayed according byRGBA hex value

let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo.ByteOrder32Big.rawValue | CGImageAlphaInfo.PremultipliedLast.rawValue)


let bitmap = CGBitmapContextCreate(nil, 192, 192, 8, 0, colorSpace,bitmapInfo.rawValue)

let bitmapData = UnsafeMutablePointer<UInt32>(CGBitmapContextGetData(bitmap))
var j = 0
for var i = 0; i < 192; i++ {
for j = 0; j < 192; j = j + 16 {
for var k = 0; k < 16; k++ {

let offset = matrix.rows * i + j + k
if(k < 4){
bitmapData[offset] = 0xff0000ff //red
}
else{
bitmapData[offset] = 0xffff00ff //yellow
}
}
}
}

let imageRef = CGBitmapContextCreateImage(bitmap)
let image = UIImage(CGImage: imageRef!)


Above is my code for create an image from raw pixels. I set color is 0xff0000ff and 0xffff00ff. However, when the image displayed in the UIimageview, it display some random color or is not able to display color.

For example, currenctly the color are 0xffff00ff and 0xff0000ff, but what my app displayed like this:

enter image description here

Does anybody know how to set up color to bitmap?

Answer Source

I see red and magenta in your output. You say you used color values 0xffff00ff and 0xff0000ff. Therefore I deduce that the byte order in your bitmap is ABGR.

If you change your bitmapInfo to CGBitmapInfo.ByteOrder32Little.rawValue | CGImageAlphaInfo.PremultipliedLast.rawValue, you'll get the byte order you expect.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download