-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFlagIcons.swift
326 lines (265 loc) · 11.5 KB
/
FlagIcons.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
//
// FlagIcons.swift
// LastDay
//
// Created by Mateusz Malczak on 17/09/16.
// Copyright © 2016 The Pirate Cat. All rights reserved.
//
import Foundation
import UIKit
/**
SpriteSheet class represents an image map
*/
open class SpriteSheet {
typealias GridSize = (cols: Int, rows: Int)
typealias ImageSize = (width: Int, height: Int)
/**
Struct stores information about a grid size, sprite size and country codes included in sprite sheet
*/
struct SheetInfo {
fileprivate(set) var gridSize: GridSize
fileprivate(set) var spriteSize: ImageSize
fileprivate(set) var codes: [String]
}
fileprivate(set) var info: SheetInfo
fileprivate(set) var image: UIImage
fileprivate(set) var colorSpace: CGColorSpace
fileprivate var imageData: UnsafeMutableRawPointer?
fileprivate var imageCache = [String:UIImage]()
fileprivate var cgImage: CGImage {
return image.cgImage!
}
var bitsPerComponent: Int {
return cgImage.bitsPerComponent
}
var bitsPerPixel: Int {
return bitsPerComponent * 4
}
var imageSize: CGSize {
return image.size
}
var spriteBytesPerRow: Int {
return 4 * info.spriteSize.width
}
var spriteBytesCount: Int {
return spriteBytesPerRow * info.spriteSize.height
}
var sheetBytesPerRow: Int {
return spriteBytesPerRow * info.gridSize.rows
}
var sheetBytesPerCol: Int {
return spriteBytesCount * info.gridSize.cols
}
var sheetBytesCount: Int {
return sheetBytesPerRow * Int(imageSize.height)
}
var bitmapInfo: CGBitmapInfo {
let imageBitmapInfo = cgImage.bitmapInfo
let imageAlphaInfo = cgImage.alphaInfo
return CGBitmapInfo(rawValue:
(imageBitmapInfo.rawValue & (CGBitmapInfo.byteOrderMask.rawValue)) |
(imageAlphaInfo.rawValue & (CGBitmapInfo.alphaInfoMask.rawValue)))
}
var bytes: UnsafeMutablePointer<UInt8> {
return imageData!.assumingMemoryBound(to: UInt8.self)
}
init?(sheetImage: UIImage, info sInfo: SheetInfo) {
image = sheetImage
info = sInfo
guard let cgImage = sheetImage.cgImage else {
return nil
}
guard let cgColorSpace = cgImage.colorSpace else {
return nil
}
colorSpace = cgColorSpace
let memory = sheetMemoryLayout()
let bytes = UnsafeMutableRawPointer.allocate(byteCount: memory.size,
alignment: memory.alignment)
let imageWidth = Int(imageSize.width)
let imageHeight = Int(imageSize.height)
guard let bmpCtx = CGContext(data: bytes,
width: imageWidth,
height: imageHeight,
bitsPerComponent: bitsPerComponent,
bytesPerRow: 4 * imageWidth,
space: colorSpace,
bitmapInfo: bitmapInfo.rawValue) else {
bytes.deallocate()
return
}
imageData = bytes
bmpCtx.draw(cgImage,
in: CGRect(x: 0, y: 0,
width: imageSize.width,
height: imageSize.height))
}
open func getImageFor(_ code: String, deepCopy: Bool = false, scale: CGFloat = 2) -> UIImage? {
var cimg = imageCache[code] // cache is not thread safe
if nil == cimg || deepCopy {
let data = getBytesFor(code)
if deepCopy {
guard let bmpCtx = CGContext(data: nil,
width: info.spriteSize.width,
height: info.spriteSize.height,
bitsPerComponent: bitsPerComponent,
bytesPerRow: spriteBytesPerRow,
space: colorSpace,
bitmapInfo: bitmapInfo.rawValue) else {
return nil
}
if let bmpData = bmpCtx.data {
var srcData = UnsafeMutablePointer<UInt8>(mutating: data.bytes)
var curData = bmpData.assumingMemoryBound(to: UInt8.self)
for _ in 0..<info.spriteSize.height {
curData.assign(from: srcData, count: spriteBytesPerRow)
curData = curData.advanced(by: spriteBytesPerRow)
srcData = srcData.advanced(by: sheetBytesPerRow)
}
if let bmpImage = bmpCtx.makeImage() {
return UIImage(cgImage: bmpImage, scale: scale, orientation: UIImage.Orientation.up).withRenderingMode(.alwaysOriginal)
}
}
return nil
}
let expectedSize = sheetBytesPerRow * info.spriteSize.height
let size = min(expectedSize, data.size)
guard let provider = CGDataProvider(dataInfo: nil,
data: data.bytes,
size: size,
releaseData: {_,_,_ in}) else {
return nil
}
guard let cgImage = CGImage(width: info.spriteSize.width,
height: info.spriteSize.height,
bitsPerComponent: bitsPerComponent,
bitsPerPixel: bitsPerPixel,
bytesPerRow: sheetBytesPerRow,
space: colorSpace,
bitmapInfo: bitmapInfo,
provider: provider,
decode: nil,
shouldInterpolate: true,
intent: CGColorRenderingIntent.defaultIntent) else {
return nil
}
cimg = UIImage(cgImage: cgImage)
imageCache[code] = cimg
}
return cimg
}
open func getBytesFor(_ code: String) -> (bytes: UnsafePointer<UInt8>, size: Int) {
let idx = info.codes.firstIndex(of: code.lowercased()) ?? 0
let dx = idx % info.gridSize.cols
let dy = idx / info.gridSize.rows
let bytesOffset = sheetBytesPerCol * dy + spriteBytesPerRow * dx
let data = bytes.advanced(by: bytesOffset)
let totalMemory = sheetMemoryLayout().size
#if TRACK_MEMORY
print("""
/*********
code : \(code)
index : \(idx)
d(x/y) : \(dx) x \(dy) | \(idx % info.gridSize.cols) x \(idx/info.gridSize.rows)
bytes offset : \(bytesOffset)
Sheet
sprites : \(info.codes.count)
grid size : \(info.gridSize.cols) x \(info.gridSize.rows)
sprite size : \(info.spriteSize.width) x \(info.spriteSize.height)
bits/Component : \(bitsPerComponent)
bits/Pixel : \(bitsPerPixel)
Memory
total : \(totalMemory)
provider : \(sheetBytesPerRow * info.spriteSize.height)
sprite : \(spriteBytesCount)
left : \(totalMemory - bytesOffseTRACK_MEMORYt)
""")
#endif
return (UnsafePointer<UInt8>(data), totalMemory - bytesOffset)
}
open func flushCache() {
imageCache.removeAll()
}
func sheetMemoryLayout() -> (size: Int, alignment: Int) {
return (sheetBytesCount * MemoryLayout<UInt8>.stride,
MemoryLayout<UInt8>.alignment)
}
deinit {
imageCache.removeAll()
if let data = imageData {
data.deallocate()
}
imageData = nil
}
}
/**
Represents a flags icon sprite sheet
*/
open class FlagIcons {
public struct Country {
public let name: String;
public let code: String;
}
open class func loadDefault() -> SpriteSheet? {
guard let assetsBundle = assetsBundle() else {
return nil
}
if let infoFile = assetsBundle.path(forResource: "flags", ofType: "json") {
return self.loadSheetFrom(infoFile)
}
return nil
}
open class func loadCountries() -> [Country]? {
guard let assetsBundle = assetsBundle() else {
return nil
}
if let dataFile = assetsBundle.path(forResource: "countries", ofType: "json") {
if let countriesSet: [[String:String]] = loadJSON(file: dataFile) {
return countriesSet.compactMap({countryInfo in
guard case let (name?, code?) = (countryInfo["name"], countryInfo["code"]) else {
return nil
}
return Country(name: name, code: code)
}).sorted(by: {country1, country2 in country1.name < country2.name})
}
}
return nil
}
open class func loadSheetFrom(_ file: String) -> SpriteSheet? {
guard let assetsBundle = assetsBundle() else {
return nil
}
if let infoObj: [String:Any] = loadJSON(file: file) {
if let gridSizeObj = infoObj["gridSize"] as? [String:Int],
let spriteSizeObj = infoObj["spriteSize"] as? [String:Int] {
let gridSize = (gridSizeObj["cols"]!, gridSizeObj["rows"]!)
let spriteSize = (spriteSizeObj["width"]!, spriteSizeObj["height"]!)
if let codes = (infoObj["codes"] as? String)?.components(separatedBy: "|") {
if let sheetFileName = infoObj["sheetFile"] as? String,
let resourceUrl = assetsBundle.resourceURL {
let sheetFileUrl = resourceUrl.appendingPathComponent(sheetFileName)
if let image = UIImage(contentsOfFile: sheetFileUrl.path) {
let info = SpriteSheet.SheetInfo(gridSize: gridSize, spriteSize: spriteSize, codes: codes)
return SpriteSheet(sheetImage: image, info: info)
}
}
}
}
}
return nil
}
fileprivate class func loadJSON<T>(file: String) -> T? {
guard let data = try? Data(contentsOf: URL(fileURLWithPath: file)) else {
return nil
}
let options = JSONSerialization.ReadingOptions(rawValue: 0)
return try? JSONSerialization.jsonObject(with: data, options: options) as? T
}
fileprivate class func assetsBundle() -> Bundle? {
let bundle = Bundle(for: self)
guard let assetsBundlePath = bundle.path(forResource: "assets", ofType: "bundle") else {
return nil
}
return Bundle(path: assetsBundlePath);
}
}