This is really a math question, so it might be debatable whether it really "belongs" on Stack Overflow, but anyway: you need to project the coordinates of each point in the image onto the axis of your gradient and use that coordinate to determine the color.
Mathematically, what I mean is:
- Say your starting point is (x1, y1) and your ending point is (x2, y2)
- Compute
A = (x2 - x1)
andB = (y2 - y1)
- Calculate
C1 = A * x1 + B * y1
for the starting point andC2 = A * x2 + B * y2
for the ending point (C2
should be larger thanC1
) - For each point in the image, calculate
C = A * x + B * y
If
C <= C1
, use the starting color; ifC >= C2
, use the ending color; otherwise, use a weighted average:(start_color * (C2 - C) + end_color * (C - C1))/(C2 - C1)
I did some quick tests to check that this basically worked.