The task seems simple: I need to draw a chart where every x coordinate has only one y coordinate (so it is a line). When it is drawn, a user can touch that chart and on the position he touched I should draw, let's say, a green circle. But it should be drawn on that chart:
Is it even possible? I tried to use PathMeasure
, but all I can get is the Y coordinate for the distance, which is not what I want. If it's not possible with Path
s, maybe there is another way of doing it?
It's a problem of geometry, finding the equation coefficients for a straight line passing through two points .
First you need to get the endpoints of the segment intersecting the vertical line containing the touch point (T[tx, ty]) namely: the point P[px, py] with the maximum x less than touched tx and the point Q[qx, qy] with the minimum x greater than tx
@NonNull
Point[] findSegment(@NonNull Point touched, Point[] dataPoints) {
Point[] segment = new Point[2];
if (dataPoints != null && dataPoints.length >= 2) {
segment[0] = dataPoints[0];
int i = 1;
while (i < dataPoints.length && p.x < touched.x) {
segment[0] = p;
i++;
}
if (i < dataPoints.length - 1) {
segment[1] = dataPoints[i];
}
}
return segment;
}
//where Point is a class with two numeric fields
class Point {
public double x;
public double y;
}
Then you need to compute the coefficients for the equation of the straight line (y = m * x + n) containing the segment using the two endpoints chosen previously:
The slope (gradient) is
m = (segment[0].y - segment[1].y) / (segment[0].x - segment[1].x);
The y intersect is
n = segment[0].y - m * segment[0].x // derived from y - y0 = m (x - x0) where x = 0 (at intersection with the vertical axis)
Then just compute y for the center of the circle using the equation replacing x by touched.x
touched.y = m * touched.x + n;
Take care to handle special cases: touched.x < firstPoint.x or touched.x > lastPoint.x (if that can occur) if you have vertical segments (trying to compute slope produces infinity or division by zero)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.