Get lighter and darker color variations for a given UIColor

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

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

11条回答
  •  面向向阳花
    2021-01-30 02:48

    SwiftUI: Color - iOS 14 / macOS 10.16

    extension Color {
        public func lighter(by amount: CGFloat = 0.2) -> Self { Self(UIColor(self).lighter(by: amount)) }
        public func darker(by amount: CGFloat = 0.2) -> Self { Self(UIColor(self).darker(by: amount)) }
    }
    

    Reqires one of the followings (or both) for iOS or (and) macOS


    AppKit: NSColor

    extension NSColor {
        func mix(with color: NSColor, amount: CGFloat) -> Self {
            var red1: CGFloat = 0
            var green1: CGFloat = 0
            var blue1: CGFloat = 0
            var alpha1: CGFloat = 0
    
            var red2: CGFloat = 0
            var green2: CGFloat = 0
            var blue2: CGFloat = 0
            var alpha2: CGFloat = 0
    
            getRed(&red1, green: &green1, blue: &blue1, alpha: &alpha1)
            color.getRed(&red2, green: &green2, blue: &blue2, alpha: &alpha2)
    
            return Self(
                red: red1 * CGFloat(1.0 - amount) + red2 * amount,
                green: green1 * CGFloat(1.0 - amount) + green2 * amount,
                blue: blue1 * CGFloat(1.0 - amount) + blue2 * amount,
                alpha: alpha1
            )
        }
    
        func lighter(by amount: CGFloat = 0.2) -> Self { mix(with: .white, amount: amount) }
        func darker(by amount: CGFloat = 0.2) -> Self { mix(with: .black, amount: amount) }
    }
    

    UIKit: UIColor

    extension UIColor {
        func mix(with color: UIColor, amount: CGFloat) -> Self {
            var red1: CGFloat = 0
            var green1: CGFloat = 0
            var blue1: CGFloat = 0
            var alpha1: CGFloat = 0
    
            var red2: CGFloat = 0
            var green2: CGFloat = 0
            var blue2: CGFloat = 0
            var alpha2: CGFloat = 0
    
            getRed(&red1, green: &green1, blue: &blue1, alpha: &alpha1)
            color.getRed(&red2, green: &green2, blue: &blue2, alpha: &alpha2)
    
            return Self(
                red: red1 * CGFloat(1.0 - amount) + red2 * amount,
                green: green1 * CGFloat(1.0 - amount) + green2 * amount,
                blue: blue1 * CGFloat(1.0 - amount) + blue2 * amount,
                alpha: alpha1
            )
        }
    
        func lighter(by amount: CGFloat = 0.2) -> Self { mix(with: .white, amount: amount) }
        func darker(by amount: CGFloat = 0.2) -> Self { mix(with: .black, amount: amount) }
    }
    

提交回复
热议问题