Skip to content

Commit

Permalink
func setSystemImage(_ systemName: String, tintColor: CAColor? = nil, …
Browse files Browse the repository at this point in the history
…newSize: CGSize? = nil)
  • Loading branch information
RomanPodymov committed Jan 21, 2024
1 parent d111086 commit 2495acd
Showing 1 changed file with 6 additions and 5 deletions.
11 changes: 6 additions & 5 deletions Sources/CommonAppleKit/CommonAppleKit.swift
Original file line number Diff line number Diff line change
Expand Up @@ -223,23 +223,23 @@
#endif

public extension CAButton {
func setSystemImage(_ systemName: String, tintColor: CAColor? = nil) {
func setSystemImage(_ systemName: String, tintColor: CAColor? = nil, newSize: CGSize? = nil) {
let image: CAImage?
if #available(macOS 11.0, iOS 13.0, tvOS 13.0, *) {
image = CAImage(systemName: systemName)
} else {
image = nil
}
if let image {
setImage(tintColor.map { image.withTint(color: $0) } ?? image)
setImage(tintColor.map { image.withTint(color: $0, newSize: newSize) } ?? image)
} else {
setTitle(systemName)
}
}
}

private extension CAImage {
func withTint(color: CAColor) -> CAImage {
func withTint(color: CAColor, newSize: CGSize? = nil) -> CAImage {
#if canImport(AppKit)
.init(size: size, flipped: false) { rect -> Bool in
color.set()
Expand All @@ -249,9 +249,10 @@ private extension CAImage {
}
#elseif canImport(UIKit)
defer { UIGraphicsEndImageContext() }
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let sizeToUse = newSize ?? size
UIGraphicsBeginImageContextWithOptions(sizeToUse, false, scale)
color.set()
withRenderingMode(.alwaysTemplate).draw(in: CGRect(origin: .zero, size: size))
withRenderingMode(.alwaysTemplate).draw(in: CGRect(origin: .zero, size: sizeToUse))
return UIGraphicsGetImageFromCurrentImageContext() ?? self
#endif
}
Expand Down

0 comments on commit 2495acd

Please sign in to comment.