如何绘制斜矩形
绘制斜矩形,并且能得到这个斜矩形的面积..
各位大侠,给个思路与做法...
在此谢谢
------解决方案--------------------
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
public class DrawTool extends Canvas{
protected void paint(Graphics g) {
g.setColor(0x000000);
try {
drawPAR(10, 10, 40, 10, 30, 30, g);
System.out.println(this.getArea(10, 10, 40, 10, 30, 30));
} catch (
IllegalAccessException e) {
e.printStackTrace();
}
}
/**
* 获取平行四边形面积
* @param x1 起始点的X坐标
* @param y1 起始点的Y左边
* @param x2 右上角的X坐标
* @param y2 右上角的Y坐标
* @param x3 右下角的X坐标
* @param y3 右下角的Y坐标
* @return 菱形面积
*/
public int getArea(int x1,int y1,int x2,int y2,int x3,int y3){
int v = distPointToLine(y3,y3,10,10,40,10); //垂直线
int base = distPointToPoint(x1, y1, x2, y2); //底边
return v*base;
}
/**
* 绘制平行四边形
* @param x1 起始点的X坐标
* @param y1 起始点的Y坐标
* @param x2 右上端点的X坐标
* @param y2 右上端点的Y坐标
* @param x3 右下端点的X坐标
* @param y3 右下端点的Y坐标
* @param g 画笔
* @throws IllegalAccessException
*/
public void drawPAR(int x1,int y1,int x2,int y2,int x3, int y3,Graphics g) throws IllegalAccessException{
float k = (y2 - y1)/(float)(x2 - x1);
float k1 = (y3 - y2)/(float)(x3 - x2);
if(k == k1)
throw new IllegalAccessException();
g.drawLine(x1, y1, x2, y2);
g.drawLine(x2, y2, x3, y3);
int x4 = x1 - x2 + x3;
int y4 = y1 - y2 + y3;
g.drawLine(x1, y1, x4, y4);
g.drawLine(x4, y4, x3, y3);
}
/**
* 获取点到直线的距离
* @param x0 点的X坐标
* @param y0 点的Y坐标
* @param x1 直线的起始点X坐标
* @param y1 直线的起始点Y坐标
* @param x2 直线的终点的X坐标
* @param y2 直线的终点的Y坐标
* @return
*/
public int distPointToLine(int x0, int y0, int x1, int y1, int x2, int y2)
{
int A = y2 - y1;
int B = x1 - x2;
int C = x2*y1 - x1*y2;
return Math.abs(A*x0 + B*y0 + C) / distPointToPoint(x2,y2,x1,y1);
}
/**
* 获取点到点的距离
* @param x1 起始点的X坐标
* @param y1 起始点的Y坐标
* @param x2 终点的X坐标
* @param y2 终点的Y坐标
* @return
*/
private int distPointToPoint(int x1,int y1,int x2,int y2) {
int dx = Math.abs(x1 - x2);
int dy = Math.abs(y1 - y2);
return sqrt((dx*dx + dy*dy));
}
double Sqrt(double d)
{
double tolerance = 0.00001;
double x, nx = 0.0;
if(d < tolerance) return 0.0;
x = d;
while(true) {
nx = 0.5 * (x + d / x);
if(Math.abs(x - nx) < tolerance) break;
x = nx;
}
return nx;
}
public int sqrt(int n) {
int r, l, t; //r: 方根; l: 余数; t: 试除数;
if (n < 100) {
r = 9;
while (n < r * r)
r--;
} else {
r = sqrt(n / 100);
l = n - r * r * 100;
t = l / (r * 20);
while (t * (r * 20 + t) > l) {
t--;
}
r = r * 10 + t;
}
return r;
}
}