views:

198

answers:

2

I have this algorithm here:

pc = # the point you are coloring now
p0 = # start point
p1 = # end point
v = p1 - p0
d = Length(v)
v = Normalize(v) # or Scale(v, 1/d)

v0 = pc - p0

t = Dot(v0, v)
t = Clamp(t/d, 0, 1)

color = (start_color * t) + (end_color * (1 - t))

to generate point to point linear gradients. It works very well for me. I was wondering if there was a similar algorithm to generate radial gradients. By similar, I mean one that solves for color at point P rather than solve for P at a certain color (where P is the coordinate you are painting).

Thanks

A: 

Based on the comment, what you want can still be viewed as a linear gradient -- i.e. you have a line from the center to the outside of the circle, and you have a linear gradient along that line. As such, the calculation is virtually identical to what you already had.

Edit: Okay, apparently I misunderstood what you want. To figure a gradient running around a radius, you still basically linearize it -- figure out the circumference at that radius (2*Pi*R), and then do a linear interpolation along a line of that length.

Jerry Coffin
Well, I want like Photoshop's radial gradient
Milo
It's kinda like a circular linear gradient
Milo
"It's kinda like a circular linear gradient": thank you, sir, you've just made my day complete. :)
avakar
Yea I knew how but how could I do it similar to what I already have?
Milo
Do you mean the angular gradient then? Take a look at http://iit.bloomu.edu/vthc/photoshop/drawing/gradients.htm and tell us.
Justin Peel
Oh, yea, that's the one! Is there a way I can modify what I have to achieve this?
Milo
Sure, it's just another way of calculating `t` from `x` and `y`.
MSalters
A: 

Linerise over atan2(dy,dx) where dx is x-center, and dy is y-center.

cx # center x
cy # center y

r1 # ring is defined by two radius
r2 #  r1 < r2

c1 # start color
c2 # stop color

ang # start angle 

px # currect point x,y
py 
if( px^2 + py^2 <= r2^2 AND px^2 + py^2 >= r1^2  )  # lies in ring?
    t= atan2(py-cy,px-cx)+ang
    t= t+ pi # atan2 is from -pi to pi
    if (t > 2* pi) # it might over 2pi becuse of +ang
       t=t-2*pi
    t=t/(2*pi) # normalise t from 0 to 1
    color = (c1 * t) + (c2 * (1 - t))

Problem whit this algorhitm is that ang is actualy wrong and should be rotated by pi and normalized between 0 and 2pi.

ralu
How can I remove the aliasing on it?
Milo