Skip to content

Instantly share code, notes, and snippets.

@rothomp3
Last active January 1, 2020 17:09
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rothomp3/0a7b9fef4249a4f91fc6 to your computer and use it in GitHub Desktop.
Save rothomp3/0a7b9fef4249a4f91fc6 to your computer and use it in GitHub Desktop.
Swift example of writing to memory buffer
let bitmapBuffer = UnsafePointer<UInt8>.alloc(Int(height * width * 4))
let pixelNumber = (x * 4) + (y * width * 4)
bitmapBuffer[pixelNumber + 3] = 255 // Alpha
bitmapBuffer[pixelNumber + 2] = redValue
bitmapBuffer[pixelNumber + 1] = greenValue
bitmapBuffer[pixelNumber + 0] = blueValue
@mattneub
Copy link

Very helpful, thanks.

@RLovelett
Copy link

I think this is missing a dealloc. Or put another way; I think this is leaking memory.

Using Swift 2 syntax I think this is a little bit better:

let bufferSize = Int(height * width * 4)
let bitmapBuffer = UnsafePointer<UInt8>.alloc(bufferSize)
defer { bitmapBuffer.dealloc(bufferSize) }

let pixelNumber = (x * 4) + (y * width * 4)

bitmapBuffer[pixelNumber + 3] = 255 // Alpha
bitmapBuffer[pixelNumber + 2] = redValue
bitmapBuffer[pixelNumber + 1] = greenValue
bitmapBuffer[pixelNumber + 0] = blueValue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment