将原始ARGB pixeldata转换为UIImage

时间:2015-04-01 00:11:19

标签: swift uiimage core-graphics cgimage argb

我希望能够将屏幕上的所有像素设置为特定颜色。我正在使用的方法是创建原始数据数组中的所有像素,然后创建一个UIImage,我放在UIImageView中。我把代码裁剪到了仍然显示问题的代码,我想通过创建图像我做了一些愚蠢的事情但是我已经阅读了所有文档并且imho一切似乎都很好:

用于保存pixeldata的结构

public struct PixelData {
    var a: UInt8 = 255
    var r: UInt8
    var g: UInt8
    var b: UInt8
}

填充数组左半部分红色,右半部分黑色

func halfRood()->[PixelData] {
        var data: [PixelData] = []

        for(var i = 0; i < Int(Constants.Resolution.x); i++) {
            for(var j = 0; j < Int(Constants.Resolution.y); j++) {
                if(j < Int(Constants.Resolution.y/2)) {
                    data.append(PixelData(a: 255, r: 255, g: 0, b: 0))
                } else {
                    data.append(PixelData(a: 255, r: 0, g: 0, b: 0))
                }

            }
        }

        return data
    }

从位图返回图像

func imageFromARGB32Bitmap(pixels: [PixelData], width: UInt, height: UInt) -> UIImage? {
    let bitsPerComponent: UInt = 8
    let bitsPerPixel: UInt = 32
    let rgbColorSpace = CGColorSpaceCreateDeviceRGB()
    let bitmapInfo:CGBitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedFirst.rawValue)

    var data = pixels
    let providerRef = CGDataProviderCreateWithCFData(NSData(bytes: &data, length: data.count * sizeof(PixelData)))
    let providerRefthing: CGDataProvider = providerRef
    let cgImage = CGImageCreate(width, height, bitsPerComponent, bitsPerPixel, width * UInt(sizeof(PixelData)), rgbColorSpace, bitmapInfo, providerRef, nil, true, kCGRenderingIntentDefault)
    let cgiimagething: CGImage = cgImage
    return UIImage(CGImage: cgImage)
}

最后设置updateUI()函数

func updateUI() {
        let data = halfRood()
        if let image = imageFromARGB32Bitmap(data, width: UInt(Constants.Resolution.x), height: UInt(Constants.Resolution.y)) {
            imageView?.image = image
        }
    }

输出如下图所示,而我期望的是: [红色的一半|黑色的一半]

currentSituation

1 个答案:

答案 0 :(得分:2)

CoreGraphics期望像素数据为行而非列。只需翻转你的for语句:

func halfRood()->[PixelData] {
    var data: [PixelData] = []
    for(var y = 0; y < Int(Constants.Resolution.y); y++) {
        for(var x = 0; x < Int(Constants.Resolution.x); x++) {
            if(y < Int(Constants.Resolution.y/2)) {
                data.append(PixelData(a: 255, r: 255, g: 0, b: 0))
            } else {
                data.append(PixelData(a: 255, r: 0, g: 0, b: 0))
            }
        }
    }

    return data
}