设我想画一个顶点坐标为(x1,y1),(x2,y2),宽度为w的倾斜矩形,则三角形长度L1为,长宽比例r = w / L1
那么,代表宽的边分别设为(x1,y1),(x3,y3)和(x2,y2),(x4,y4),线条之间互相垂直,根据相似三角形关系容易知道:
x3 = x1 + |y2 - y1| * r
y3 = y1 + |x2 - x1| * r
x4 = x2 + |y2 - y1| * r
y4 = y2 + |x2 - x1| * r
根据斜率的不同,x3,x4,y3,y4对于x1,x2,y1,y2的偏移值符号是不同的,具体代码如下,可以允许你使用Bitmap或者二维数组实现任意角度的矩形的绘制:
// Bresenham's line algorithm
private void drawLine(Bitmap bitmap, int x1, int y1, int x2, int y2, int color) {
// 参数 color 为颜色值
int dx = Math.abs(x2 - x1),
dy = Math.abs(y2 - y1),
yy = 0;
//如果dx小于dy,则x,y系列交换
if (dx < dy) {
yy = 1;
//各种交换
{
x1 ^= y1;
y1 ^= x1;
x1 ^= y1;
}
{
x2 ^= y2;
y2 ^= x2;
x2 ^= y2;
}
{
dx ^= dy;
dy ^= dx;
dx ^= dy;
}
}
int ix = (x2 - x1) > 0 ? 1 : -1,
iy = (y2 - y1) > 0 ? 1 : -1,
cx = x1,
cy = y1,
n2dy = dy * 2,
n2dydx = (dy - dx) * 2,
d = dy * 2 - dx;
if (yy > 0) { // 如果直线与 x 轴的夹角大于 45 度
while (cx != x2) {
if (d < 0) {
d += n2dy;
} else {
cy += iy;
d += n2dydx;
}
//putpixel(img, cy, cx, color);
if(cy >= 0 && cy < bitmap.getWidth() && cx >= 0 && cx < bitmap.getHeight()) {
bitmap.setPixel(cy, cx, color);
}
cx += ix;
}
} else { // 如果直线与 x 轴的夹角小于 45 度
while (cx != x2) {
if (d < 0) {
d += n2dy;
} else {
cy += iy;
d += n2dydx;
}
//putpixel(img, cx, cy, color);
if(cx >= 0 && cx < bitmap.getWidth() && cy >= 0 && cy < bitmap.getHeight()) {
bitmap.setPixel(cx, cy, color);
}
cx += ix;
}
}
}
// Bresenham's line algorithm
private void drawRect(Bitmap bitmap, int x1, int y1, int x2, int y2, int color, int width) {
if(getVericalLinesSlope(new float[]{x1, y1}, new float[]{x2, y2}) < 0){
drawLine(bitmap, x1, y1, x2, y2, color);
double length = Math.sqrt(Math.pow(y2 - y1, 2) + Math.pow(x2 - x1, 2));
double dy = Math.abs(y2 - y1);
double dx = Math.abs(x2 - x1);
double ratioToLength = width / length;
drawLine(bitmap, x1, y1, (int)(x1 + dy * ratioToLength), (int)(y1 + dx * ratioToLength), color);
drawLine(bitmap, (int)(x1 + dy * ratioToLength), (int)(y1 + dx * ratioToLength), (int)(x2 + dy * ratioToLength), (int)(y2 + dx * ratioToLength), color);
drawLine(bitmap, x2, y2, (int)(x2 + dy * ratioToLength), (int)(y2 + dx * ratioToLength), color);
} else {
drawLine(bitmap, x1, y1, x2, y2, color);
double length = Math.sqrt(Math.pow(y2 - y1, 2) + Math.pow(x2 - x1, 2));
double dy = Math.abs(y2 - y1);
double dx = Math.abs(x2 - x1);
double ratioToLength = width / length;
drawLine(bitmap, x1, y1, (int)(x1 - dy * ratioToLength), (int)(y1 + dx * ratioToLength), color);
drawLine(bitmap, (int)(x1 - dy * ratioToLength), (int)(y1 + dx * ratioToLength), (int)(x2 - dy * ratioToLength), (int)(y2 + dx * ratioToLength), color);
drawLine(bitmap, x2, y2, (int)(x2 - dy * ratioToLength), (int)(y2 + dx * ratioToLength), color);
}
}
/**输入一根线,得到线的斜率**/
private float getVericalLinesSlope(float lineHeadLoc[], float lineEndLoc[]){
float dy = lineEndLoc[1] - lineHeadLoc[1];
float dx = lineEndLoc[0] - lineHeadLoc[0];
if(dx == 0){
dx = Float.MIN_VALUE;
}
float slope = (dy / dx); //斜率计算
return slope ;
}
实现效果: