Skip to content

Instantly share code, notes, and snippets.

@pj4533
Created July 1, 2023 14:03
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 pj4533/d31595504f95d9429d7c95b575d233e7 to your computer and use it in GitHub Desktop.
Save pj4533/d31595504f95d9429d7c95b575d233e7 to your computer and use it in GitHub Desktop.
An empty CGImage based on another CGImage
func createBlackCGImage(basedOn originalImage: CGImage) -> CGImage? {
let width = originalImage.width
let height = originalImage.height
let bitsPerComponent = originalImage.bitsPerComponent
let bytesPerRow = originalImage.bytesPerRow
let colorSpace = originalImage.colorSpace ?? CGColorSpace(name: CGColorSpace.sRGB)!
let bitmapInfo = originalImage.bitmapInfo
// Create an empty context with the same parameters as the original image
guard let context = CGContext(data: nil,
width: width,
height: height,
bitsPerComponent: bitsPerComponent,
bytesPerRow: bytesPerRow,
space: colorSpace,
bitmapInfo: bitmapInfo.rawValue) else {
return nil
}
// Fill the context with black color
context.setFillColor(CGColor.black)
context.fill(CGRect(x: 0, y: 0, width: width, height: height))
// Create a new CGImage from the context
return context.makeImage()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment