Skip to content

Instantly share code, notes, and snippets.

@chriseidhof
Created June 14, 2015 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chriseidhof/6af00505acbedf0159a4 to your computer and use it in GitHub Desktop.
Save chriseidhof/6af00505acbedf0159a4 to your computer and use it in GitHub Desktop.
CGBitmapContext
// Here we provide the structure of our bitmap context
struct BitmapContextConfig {
var bitsPerComponent: Int
var bytesPerPixel: Int
var space: CGColorSpace
var bitmapInfo: CGBitmapInfo
var data: UnsafeMutablePointer<Void> = nil
}
// A default gray context
let grayContext: BitmapContextConfig = {
let space = CGColorSpaceCreateWithName(kCGColorSpaceGenericGray)!
let bitmapInfo = CGBitmapInfo()
return BitmapContextConfig(bitsPerComponent: 8, bytesPerPixel: 8, space: space, bitmapInfo: bitmapInfo, data: nil)
}()
// A default RGB context
let rgbContext: BitmapContextConfig = {
let space = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB)!
let info = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue)
return BitmapContextConfig(bitsPerComponent: 8, bytesPerPixel: 4, space: space, bitmapInfo: info, data: nil)
}()
// Creating a new context
func createContext(width: Int, height: Int, config: BitmapContextConfig) -> CGContext? {
return CGBitmapContextCreate(config.data, width, height, config.bitsPerComponent, width*config.bytesPerPixel, config.space, config.bitmapInfo.rawValue)
}
createContext(800, height: 600, config: rgbContext)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment