Skip to content

Instantly share code, notes, and snippets.

@jmcd
Last active April 15, 2024 02:58
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jmcd/a28248aca0e8f0ce486c9ab0d55f24e1 to your computer and use it in GitHub Desktop.
Save jmcd/a28248aca0e8f0ce486c9ab0d55f24e1 to your computer and use it in GitHub Desktop.
Create CGContext (then images) from raw pixel data
import QuartzCore
extension CGContext {
private static let colorSpace = CGColorSpaceCreateDeviceRGB()
private static let bitmapInfo =
CGBitmapInfo.byteOrder32Big.rawValue |
CGImageAlphaInfo.premultipliedLast.rawValue & CGBitmapInfo.alphaInfoMask.rawValue
static func from(pixels: [UInt32], width: Int) -> CGContext? {
var mutPixels = pixels
let mutBufPtr = UnsafeMutableBufferPointer(start: &mutPixels, count: pixels.count)
let height = pixels.count / width
let bytesPerRow = width * 4
return CGContext(data: mutBufPtr.baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo, releaseCallback: nil, releaseInfo: nil)
}
}
import UIKit
// 0xAABBGGRR
let b: UInt32 = 0xffff0000
let g: UInt32 = 0xff00ff00
let y: UInt32 = 0xff00ffff
let px = [
b, b, y, y,
b, b, b, y,
g, g, b, b,
g, g, g, g,
]
if let ctx = CGContext.from(pixels: px, width: 4), let cgImage = ctx.makeImage() {
let uiImage = UIImage(cgImage: cgImage)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment