2016-01-25 44 views
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) 
    } 

} 

回答

3

有幾個需要更改。 1.由於存在內存溢出而導致崩潰。 2.您從新創建的上下文創建圖像,並寫入相同的上下文而不是當前的繪圖上下文。

使用該修改的drawRect功能:

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) 

    let pixels = UnsafeMutablePointer<CUnsignedChar>(data) 
    var n = 0 
    for var j = 0; j < height; j++ { 
     for var i = 0; i < width; i++ { 
      pixels[n++] = 0 //B 
      pixels[n++] = 255 //G 
      pixels[n++] = 0 //R 
      pixels[n++] = 255 //A 
     } 
    } 
    let image = CGBitmapContextCreateImage(context!) 
    if let currentContext: CGContext! = UIGraphicsGetCurrentContext() { 
     UIImagePNGRepresentation(UIImage(CGImage:image!))?.writeToFile("/Users/admin/Desktop/aaaaa.png", atomically: true) 
     CGContextDrawImage(currentContext, boundingBox, image) 
    } 
} 
+0

我認爲我不需要調用UIImagePNGRepresentation?此外,我分配bytesPerPixel = 4,後來使用轉換爲UInt32,所以我不明白爲什麼內存崩潰。在BGRA中默認情況下是否創建了上下文? – Laurent

+1

無需調用UIImagePNGRepresentation。我已添加僅用於測試目的。你可以刪除這個。 CGBitmapContextCreate默認順序是BGRA。 –