0
我希望能夠將屏幕上的所有像素設置爲特定顏色。我正在使用的方法是創建一個原始數據數組中的所有像素,然後創建一個UIImage,我把它放在UIImageView中。我裁剪的代碼到這裏面依然呈現出這個問題,我覺得我已經做了一些愚蠢的創建圖像,但我看了所有的文件和恕我直言,一切似乎很動聽:將原始ARGB像素數據轉換爲UIImage
結構保存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
}
}
輸出類似於下面的圖片,而我希望是這樣的: [紅色半|黑色半]
這是解決方案,非常感謝! – Simon 2015-04-01 12:29:56