воскресенье, 5 января 2014 г.

Slope of a Straight Line Android

For example, you need find intersection of the line and touch. You have some line on the screen like on the pic1. 



First of all you need coordinates x1, x2, y1, y2. These are coordinates of start and end of the line.
The equation of the line contents coefficients a,b. The screen of android gives you coodinates but the y should be calculated in -1.
So here is function:
public float[] equation() {
float a = y2 - y1;
float b = mX1 - mX2;
float k = 0;
float d = 0;

if (b != 0) {
k = (y2 - y1) / (x1 - x2);
d = (x2 * y1 - x1 * y2) / (x1 - x2);
} else {
k = 0;
d = x1;
}

if (a == 0) {
k = y1;
d = 0;
}
return new float[]{k, d};
}

The points of intersections can be found with help of previously found coefficients. Next function takes 2 floats arrays with coefficients of each line. The function has different solutions for vertical straight, horizontal and the other straight.
public float[] intersection(float[] koef1, float[] koef2) {
float x = 0;
float y = 0;
// if curve is straight
// vertical
if (koef1[0] == 0 || koef2[0] == 0) {
if (koef1[0] == 0) {
x = koef1[1];
y = koef2[0] * x + koef2[1];
}
if (koef2[0] == 0) {
x = koef2[1];
y = koef1[0] * x + koef1[1];
}
return new float[]{x, y};
}
// horizontal
if (koef1[1] == 0 || koef2[1] == 0) {
if (koef1[1] == 0) {
y = koef1[0];
x = (koef2[1] - y) / koef2[0];
}
if (koef2[1] == 0) {
y = koef2[0];
x = (koef1[1] - y) / koef1[0];
}
x *= (-1);
return new float[]{x, y};
}

// simple curve
// x = (b1-b2)/(k2-k1)
if (koef2[0] - koef1[0] != 0) {
x = (koef2[1] - koef1[1]) / (koef1[0] - koef2[0]);
y = koef1[0] * x + koef1[1];
}
return new float[]{x, y};
}




Комментариев нет:

Отправить комментарий