-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBitmap.swift
More file actions
78 lines (66 loc) · 2.16 KB
/
Bitmap.swift
File metadata and controls
78 lines (66 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//
// Bitmap.swift
// FractalGenerator
//
// A bitmap class to manage pixel level drawing using CGImage
import Foundation
import QuartzCore
struct Color {
var red: Byte
var green: Byte
var blue: Byte
var alpha: Byte
}
final class Bitmap {
var width: Int
var height: Int
var bytesPerRow: Int
var data = [Byte]()
init(width: Int, height: Int) {
self.width = width
self.height = height
bytesPerRow = width * 4
data = [Byte](count: Int(width * height * 4), repeatedValue: 255)
}
func createBitmapContext () -> CGContext! {
return CGBitmapContextCreateWithData(UnsafeMutablePointer<Void>(data),
UInt(width),
UInt(height),
8,
UInt(4 * width),
CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB),
CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue),
nil, nil)
}
func drawRow(rowNumber: Int, rowData: [Byte]) {
var index = rowNumber * bytesPerRow
for b in rowData {
data[index++] = b
}
}
func drawPixel(x: Int, y: Int, c: Color) {
let offset = y * bytesPerRow + x * 4
data[offset] = c.red
data[offset + 1] = c.green
data[offset + 2] = c.blue
data[offset + 3] = c.alpha
}
func readPixel(x: Int, y: Int) -> Color {
let offset = y * bytesPerRow + x * 4
return Color(red: data[offset], green: data[offset + 1],
blue: data[offset + 2], alpha: data[offset + 3])
}
func createImage() -> CGImage! {
return CGBitmapContextCreateImage(createBitmapContext())
}
func saveImage(path: String) {
let image = createImage()
let options: [String:AnyObject] = [kCGImagePropertyOrientation : 1, // top left
kCGImagePropertyHasAlpha : true,
kCGImageDestinationLossyCompressionQuality : 1.0] // maximum quality
let url = NSURL.fileURLWithPath(path, isDirectory: false)
let file = CGImageDestinationCreateWithURL(url, kUTTypePNG, 1, nil)
CGImageDestinationAddImage(file, image, options)
CGImageDestinationFinalize(file)
}
}