Get Slightly Lighter and Darker Color from UIColor

前端 未结 19 2386
猫巷女王i
猫巷女王i 2020-12-07 07:08

I was looking to be able to turn any UIColor into a gradient. The way I am intending to do this is by using Core Graphics to draw a gradient. What I am trying to do is to ge

相关标签:
19条回答
  • 2020-12-07 07:49

    Tested in Xcode 10 with Swift 4.x for iOS 12

    Start with your color as a UIColor and pick a darkening factor (as a CGFloat)

    let baseColor = UIColor.red
    let darkenFactor: CGFloat = 2
    

    The type CGColor has an optional value components which break down the color into RGBA (as a CGFloat array with values between 0 and 1). You can then reconstruct a UIColor using RGBA values taken from the CGColor and manipulate them.

    let darkenedBase = UIColor(displayP3Red: startColor.cgColor.components![0] / darkenFactor, green: startColor.cgColor.components![1] / darkenFactor, blue: startColor.cgColor.components![2] / darkenFactor, alpha: 1)
    

    In this example, each of the RGB valuse were divided by 2, making the color half as dark as it was before. The alpha value remained the same, but you could alternatively apply the darken factor on the alpha value rather than the RGB.

    0 讨论(0)
提交回复
热议问题