Reputation: 4888
I have 256x256 Canvas
and a Polyline
on it with the first Point
with X
coordinate = 0 and last Point
with X
= 255. There may be more points in between entered by the user during run time. How can I get the Y
coordinate of each X
in the range 0 - 255 of the rendered Polyline
?
Upvotes: 1
Views: 434
Reputation: 487
Suppose the points of the polyline are (x[i], y[i]), for i = 0 to n, where the x-values are in increasing order. So, we know x[0] = 0 and x[n] = 255. Then suppose we are given an x value in the range 0 to 255. We first find an index i such that x[i] < x <= x[i+1]. Then the corresponding y value is given by
y = y[i] + (y[i+1] - y[i])*(x - x[i])/(x[i+1] - x[i])
or, equivalently
y = ( (x[i+1] - x)*y[i] + (x - x[i])*y[i+1] ) / (x[i+1] - x[i])
Of course, there will be problems if x[i] = x[i+1] so this special case requires some extra care.
Also, note that these formulae will give you non-integer values of y, which obviously don't correspond directly to any pixel location. Exactly which pixels will be rendered depends on the width of the line and the internal details of the scan conversion algorithm, which we cannot know. But, if you round the y value to an integer, there's a very good chance that the corresponding pixel will be rendered.
Upvotes: 1