/
ImageSet.swift
78 lines (61 loc) · 2.18 KB
/
ImageSet.swift
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
//
// ImageSet.swift
// Iconizer
// https://github.com/raphaelhanneken/iconizer
//
import Cocoa
class ImageSet: Codable {
//scale of input image
static let inputScale: CGFloat = 3
let idiom: String
let scale: AssetScale
var filename: String {
return "image@\(scale.rawValue).png"
}
private enum ReadKeys: String, CodingKey {
case idiom
case scale
}
private enum WriteKeys: String, CodingKey {
case idiom
case scale
case filename
}
init(idiom: String, scale: AssetScale) {
self.idiom = idiom
self.scale = scale
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: ReadKeys.self)
let idiom = try container.decode(String.self, forKey: .idiom)
guard let scale = AssetScale(rawValue: try container.decode(String.self, forKey: .scale)) else {
throw AssetCatalogError.invalidFormat(format: .scale)
}
self.idiom = idiom
self.scale = scale
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: WriteKeys.self)
try container.encode(idiom, forKey: .idiom)
try container.encode(scale.rawValue, forKey: .scale)
try container.encode(filename, forKey: .filename)
}
}
extension ImageSet: Asset {
static let resourcePrefix = "ImageSet"
static func directory(named: String) -> String {
return "\(Constants.Directory.imageSet)/\(named).\(Constants.AssetExtension.imageSet)"
}
func save(_ image: [ImageOrientation: NSImage], aspect: AspectMode?, to url: URL) throws {
guard let image = image[.all] else {
throw AssetCatalogError.missingImage
}
let url = url.appendingPathComponent(filename, isDirectory: false)
let coef = CGFloat(scale.value) / ImageSet.inputScale
let size = NSSize(width: ceil(image.size.width * coef), height: ceil(image.size.height * coef))
guard let resized = image.resize(toSize: size, aspectMode: aspect ?? .fit) else {
throw AssetCatalogError.rescalingImageFailed
}
try resized.savePng(url: url)
}
}