Swift extension example

后端 未结 8 2156
既然无缘
既然无缘 2020-11-28 01:33

I was originally wanting to know how to make something like this

UIColor.myCustomGreen

so that I could define my own colors and use them th

8条回答
  •  孤独总比滥情好
    2020-11-28 02:15

    If you like to use a colour with a given tint like used in brand manuals: Swift 4.2 + xcode 9.4.1.

    extension UIColor {
        func withTint(tint: CGFloat)->UIColor {
    
            var tint = max(tint, 0)
            tint = min(tint, 1)
            /* Collect values of sender */
            var r : CGFloat = 0
            var g : CGFloat = 0
            var b : CGFloat = 0
            var a : CGFloat = 0
            self.getRed(&r, green: &g, blue: &b, alpha: &a)
    
            /* Calculate the tint */
            r = r+(1-r)*(1-tint)
            g = g+(1-g)*(1-tint)
            b = b+(1-b)*(1-tint)
            a = 1
    
            return UIColor.init(red: r, green: g, blue: b, alpha: a)
        }
    }
    

    In your code

    let redWithTint = UIColor.red.withTint(tint: 0.4)
    

提交回复
热议问题