title: Drawing pixels on the screen using CoreGraphics in Swift
body: <p>The code below is trying to set pixels to an offline bitmap and draw the bitmap to the screen. Unfortunately, it crashes. </p>
  
  <pre><code>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) -&gt; CGContextRef? {
          let bytesPerPixel = 4
          let bytesPerRow = bytesPerPixel * pixelsWide
          let bitsPerComponent = 8
  
          let byteCount = (bytesPerRow * pixelsHigh)
  
          let colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB)
  
          let pixels = UnsafeMutablePointer&lt;CUnsignedChar&gt;.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 &lt; height; j++ {
              for var i = 0; i &lt; width; i++ {
                  currentPixel[n++] = 0
              }
          }
  
          let image = CGBitmapContextCreateImage(context!)
          CGContextDrawImage(context!, boundingBox, image)
      }
  
  }
  </code></pre>