Get lighter and darker color variations for a given UIColor

前端 未结 11 2190
一生所求
一生所求 2021-01-30 02:32

How to get different lighter and darker variations of a given UIColor in Swift?

11条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-30 02:38

    Since I use SwiftUI in my current project, I adapted the best answer from Stephen. Tested with Xcode 12.0, SwiftUI 2 and iOS 14.0

    extension Color {
        var components: (red: CGFloat, green: CGFloat, blue: CGFloat, opacity: CGFloat) {
            #if canImport(UIKit)
            typealias NativeColor = UIColor
            #elseif canImport(AppKit)
            typealias NativeColor = NSColor
            #endif
    
            var r: CGFloat = 0
            var g: CGFloat = 0
            var b: CGFloat = 0
            var o: CGFloat = 0
    
            guard NativeColor(self).getRed(&r, green: &g, blue: &b, alpha: &o) else {
                return (0, 0, 0, 0)
            }
            return (r, g, b, o)
        }
        
        func lighter(by percentage: CGFloat = 30.0) -> Color {
            return self.adjust(by: abs(percentage) )
        }
    
        func darker(by percentage: CGFloat = 30.0) -> Color {
            return self.adjust(by: -1 * abs(percentage) )
        }
    
        func adjust(by percentage: CGFloat = 30.0) -> Color {
            return Color(red: min(Double(self.components.red + percentage/100), 1.0),
                         green: min(Double(self.components.green + percentage/100), 1.0),
                         blue: min(Double(self.components.blue + percentage/100), 1.0),
                         opacity: Double(self.components.opacity))
        }
    }
    

提交回复
热议问题