2
下面的代碼試圖將像素設置爲離線位圖並將位圖繪製到屏幕上。不幸的是,它崩潰了。使用Swift中的CoreGraphics在屏幕上繪製像素
import UIKit
class GameView: UIView {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
func createBitmapContext(pixelsWide: Int, _ pixelsHigh: Int) -> CGContextRef? {
let bytesPerPixel = 4
let bytesPerRow = bytesPerPixel * pixelsWide
let bitsPerComponent = 8
let byteCount = (bytesPerRow * pixelsHigh)
let colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB)
let pixels = UnsafeMutablePointer<CUnsignedChar>.alloc(byteCount)
if pixels == nil {
return nil
}
let bitmapInfo = CGImageAlphaInfo.PremultipliedFirst.rawValue | CGBitmapInfo.ByteOrder32Little.rawValue
let context = CGBitmapContextCreate(pixels, pixelsWide, pixelsHigh, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo)
return context
}
override func drawRect(rect: CGRect) {
let width = 200
let height = 300
let boundingBox = CGRectMake(0, 0, CGFloat(width), CGFloat(height))
let context = createBitmapContext(width, height)
let data = CGBitmapContextGetData(context)
var currentPixel: [UInt32] = unsafeBitCast(data, [UInt32].self)
var n = 0
for var j = 0; j < height; j++ {
for var i = 0; i < width; i++ {
currentPixel[n++] = 0
}
}
let image = CGBitmapContextCreateImage(context!)
CGContextDrawImage(context!, boundingBox, image)
}
}
我認爲我不需要調用UIImagePNGRepresentation?此外,我分配bytesPerPixel = 4,後來使用轉換爲UInt32,所以我不明白爲什麼內存崩潰。在BGRA中默認情況下是否創建了上下文? – Laurent
無需調用UIImagePNGRepresentation。我已添加僅用於測試目的。你可以刪除這個。 CGBitmapContextCreate默認順序是BGRA。 –