Calculate the color at a given point on a gradient between two colors?

一世执手 提交于 2019-11-28 04:30:38

You simply linearly interpolate the red, the green, and the blue channels like this:

double resultRed = color1.red + percent * (color2.red - color1.red);
double resultGreen = color1.green + percent * (color2.green - color1.green);
double resultBlue = color1.blue + percent * (color2.blue - color1.blue);

where percent is a value between 0 and 1 (location in your first method prototype).

LenArt

RGB color space is like a circle. With highest saturation along the outer border, and grey in the middle. Traveling from one color to another, you'd preferably want to be doing that, along the same radius (circle) from the middle; so as to where saturation and value stay the same. In that case, the hue is changing in a linear fashion. You will not cross into more grey area than your left and right colors initially are. You can travel from an inner ring to an outer ring, simple go up (or down) the saturation; again linearly. See here for color circle (try it in e.g. paint.net)

Apple's (iOS) objective classes allow you to work with other spectra than RGB.

a Swift version may be helpful to someone.

private struct Color {
    let r: Int
    let g: Int
    let b: Int
    func getColor() -> UIColor {
        return UIColor(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: 1)
    }

    static func getGradientColor(from: Color, to: Color, percentage: CGFloat) -> Color {
        precondition(percentage >= 0 && percentage <= 1)
        return Color(r: from.r + Int(CGFloat(to.r - from.r) * percentage),
                     g: from.g + Int(CGFloat(to.g - from.g) * percentage),
                     b: from.b + Int(CGFloat(to.b - from.b) * percentage))
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!