Last active
October 3, 2021 22:45
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Note this code was correct when written (for Swift 1.0 most likely). | |
// Swift has evolved and Phill Apley has provided an updated version in the comments. | |
public struct PixelData { | |
var a:UInt8 = 255 | |
var r:UInt8 | |
var g:UInt8 | |
var b:UInt8 | |
} | |
private let rgbColorSpace = CGColorSpaceCreateDeviceRGB() | |
private let bitmapInfo:CGBitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedFirst.toRaw()) | |
public func imageFromARGB32Bitmap(pixels:[PixelData], width:UInt, height:UInt)->UIImage { | |
let bitsPerComponent:UInt = 8 | |
let bitsPerPixel:UInt = 32 | |
assert(pixels.count == Int(width * height)) | |
var data = pixels // Copy to mutable [] | |
let providerRef = CGDataProviderCreateWithCFData( | |
NSData(bytes: &data, length: data.count * sizeof(PixelData)) | |
) | |
let cgim = CGImageCreate( | |
width, | |
height, | |
bitsPerComponent, | |
bitsPerPixel, | |
width * UInt(sizeof(PixelData)), | |
rgbColorSpace, | |
bitmapInfo, | |
providerRef, | |
nil, | |
true, | |
kCGRenderingIntentDefault | |
) | |
return UIImage(CGImage: cgim) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment