Created
October 3, 2021 08:01
-
-
Save VAndrJ/c4a9093e9622f6f5455c8ee5d3598941 to your computer and use it in GitHub Desktop.
Simple wrapper to support images programmatically for different userInterfaceStyle appearance.
This file contains hidden or 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
#if canImport(UIKit) | |
import UIKit | |
@propertyWrapper | |
public struct AppearanceImage { | |
public var wrappedValue: UIImage { asset.image(with: .current) } | |
let asset: UIImageAsset | |
public init(light: UIImage, dark: UIImage) { | |
let asset = UIImageAsset() | |
asset.register(light, with: .init(userInterfaceStyle: .light)) | |
asset.register(dark, with: .init(userInterfaceStyle: .dark)) | |
self.asset = asset | |
} | |
public init(lightColor: UIColor, darkColor: UIColor, size: CGSize = .init(width: 1, height: 1)) { | |
func renderImage(from color: UIColor) -> UIImage { | |
return UIGraphicsImageRenderer(size: size).image { | |
color.setFill() | |
$0.fill(CGRect(origin: .zero, size: size)) | |
} | |
} | |
self.init(light: renderImage(from: lightColor), dark: renderImage(from: darkColor)) | |
} | |
public init(appearanceColor: UIColor, size: CGSize = .init(width: 1, height: 1)) { | |
self.init( | |
lightColor: appearanceColor.resolvedColor(with: .init(userInterfaceStyle: .light)), | |
darkColor: appearanceColor.resolvedColor(with: .init(userInterfaceStyle: .dark)), | |
size: size | |
) | |
} | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment