Skip to content

Instantly share code, notes, and snippets.

@jbruchanov
Last active November 5, 2015 10:21
Show Gist options
  • Save jbruchanov/5c684851f919fe2dcf15 to your computer and use it in GitHub Desktop.
Save jbruchanov/5c684851f919fe2dcf15 to your computer and use it in GitHub Desktop.
Line java
package com.smallplanet.android.birdsandbees.math;
import android.graphics.PointF;
/**
* Created by JBruchanov on 04/11/2015.
*/
public class Line implements Comparable<Line> {
private PointF mPoint1;
private PointF mPoint2;
//ax + by + c = 0
private float mA;
private float mB;
private float mC;
//y = kx + q, tan(fi) = k
private float mK;
private float mQ;
private float mFiDeg;
public Line(float x1, float y1, float x2, float y2) {
this(new PointF(Math.min(x1, x2), Math.min(y1, y2)), new PointF(Math.max(x1, x2), Math.max(y1, y2)));
}
private Line(PointF point1, PointF point2) {
mPoint1 = point1;
mPoint2 = point2;
build();
}
private void build() {
//u = X2 - X1 => (x2 - x1, y2 - y1)
PointF u = new PointF(mPoint2.x - mPoint1.x, mPoint2.y - mPoint1.y);
//n = u(u2, -u1) => ax+by+c=0 <=> u2x+u1y+c=0
mA = u.y;
mB = -u.x;
//getting c => c = -ax -by =>
float c1 = -(mA * mPoint1.x) - (mB * mPoint1.y);
float c2 = -(mA * mPoint2.x) - (mB * mPoint2.y);
assert c1 == c2;
mC = c1;
mK = -mA / mB;
mQ = -mC / mB;
mFiDeg = (float) Math.toDegrees(Math.atan(mK));
}
public float getY(float x) {
if (inRange(x)) {
}
return Float.NaN;
}
public boolean inRange(float x) {
return mPoint1.x <= x && x <= mPoint2.x;
}
public PointF getPoint1() {
return new PointF(mPoint1.x, mPoint1.y);
}
public PointF getPoint2() {
return new PointF(mPoint2.x, mPoint2.y);
}
public float getA() {
return mA;
}
public float getB() {
return mB;
}
public float getC() {
return mC;
}
public float getK() {
return mK;
}
public float getQ() {
return mQ;
}
public float getFiDeg() {
return mFiDeg;
}
@Override
public int compareTo(Line another) {
return Float.compare(mPoint1.x, another.mPoint1.x);
}
public String toGeneralForm() {
StringBuilder sb = new StringBuilder();
if (mA != 0) {
sb.append(String.format("%.2fX", mA));
}
if (mB != 0) {
sb.append(String.format(" %.2fY", mA));
}
if (mC != 0) {
sb.append(String.format(" %.2f", mA));
}
sb.append(" = 0");
return sb.toString().trim();
}
public String toInterceptForm() {
StringBuilder sb = new StringBuilder();
sb.append("Y = ");
if (mK != 0) {
sb.append(String.format("%.2fX", mA));
}
if (mQ != 0) {
sb.append(String.format(" %.2fY", mA));
}
return sb.toString().trim();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment