Created
November 22, 2017 07:26
-
-
Save randomsequence/7889635e19a04e9a1aa6ebf2f2223dfb to your computer and use it in GitHub Desktop.
Poking at Pixels in Swift 4
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
import Cocoa | |
struct Pixel { | |
var alpha: UInt8 | |
var red: UInt8 | |
var green: UInt8 | |
var blue: UInt8 | |
init(red: UInt8, green: UInt8, blue: UInt8, alpha: UInt8) { | |
self.alpha = alpha | |
self.red = red | |
self.green = green | |
self.blue = blue | |
} | |
static func zero() -> Pixel { | |
return self.init(red: 0, green: 0, blue: 0, alpha: 0) | |
} | |
} | |
do { | |
let width: Int = 256 | |
let height: Int = 256 | |
let count = width*height | |
let stride = MemoryLayout<Pixel>.stride | |
// let alignment = MemoryLayout<Pixel>.alignment | |
let bytesPerRow = stride*width | |
let byteCount = bytesPerRow*height | |
let pointer = UnsafeMutablePointer<Pixel>.allocate(capacity: count) | |
pointer.initialize(to: Pixel.zero(), count: count) | |
defer { | |
pointer.deinitialize(count: count) | |
pointer.deallocate(capacity: count) | |
} | |
let buffer = UnsafeMutableBufferPointer(start: pointer, count: count) | |
for (i, _) in buffer.enumerated() { | |
buffer[i].alpha = 255 | |
buffer[i].red = 0 | |
buffer[i].green = 255 | |
buffer[i].blue = 0 | |
} | |
let data = UnsafeMutableRawPointer(pointer) | |
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue) | |
let ctx = CGContext.init(data: data, | |
width: width, | |
height: height, | |
bitsPerComponent: 8, | |
bytesPerRow: bytesPerRow, | |
space: CGColorSpaceCreateDeviceRGB(), | |
bitmapInfo: bitmapInfo.rawValue) | |
if let context = ctx { | |
let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: CGFloat(width), height: CGFloat(height))).insetBy(dx: CGFloat(width)/3.0, dy: CGFloat(height)/3.0) | |
context.setFillColor(NSColor.red.cgColor) | |
context.fill(rect) | |
let image = context.makeImage() | |
let bitmap = NSBitmapImageRep.init(cgImage: image!) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment