-
Notifications
You must be signed in to change notification settings - Fork 277
/
UIImage+Icons.swift
55 lines (44 loc) · 1.81 KB
/
UIImage+Icons.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
//
// UIImage+Icons.swift
// Shared
//
// Created by Stephan Vanterpool on 9/15/18.
// Copyright © 2018 Robbie Trencheny. All rights reserved.
//
import UIKit
extension UIImage {
public convenience init(size: CGSize, color: UIColor) {
// why is UIGraphicsImageRenderer not available on watchOS?
var alpha: CGFloat = 1
color.getRed(nil, green: nil, blue: nil, alpha: &alpha)
UIGraphicsBeginImageContextWithOptions(size, alpha == 1.0, 0)
color.setFill()
UIRectFill(CGRect(origin: .zero, size: size))
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
self.init(cgImage: image.cgImage!, scale: image.scale, orientation: image.imageOrientation)
}
public static func iconForIdentifier(_ iconIdentifier: String, iconWidth: Double,
iconHeight: Double, color: UIColor) -> UIImage {
MaterialDesignIcons.register()
let mdi = MaterialDesignIcons(named: iconIdentifier.normalizingIconString, fallbackIconName: "help")
return mdi.image(ofSize: CGSize(width: CGFloat(iconWidth), height: CGFloat(iconHeight)), color: color)
}
}
public extension MaterialDesignIcons {
init(serversideValueNamed value: String, fallbackIcon: String? = nil) {
if let fallbackIcon = fallbackIcon {
self.init(named: value.normalizingIconString, fallbackIconName: fallbackIcon)
} else {
self.init(named: value.normalizingIconString)
}
}
}
internal extension String {
var normalizingIconString: String {
return self
.replacingOccurrences(of: "mdi:|hass:", with: "", options: .regularExpression)
.replacingOccurrences(of: ":", with: "_")
.replacingOccurrences(of: "-", with: "_")
}
}