java graphics drawline (make line bold, 使線變粗,兩種方式)
protected void paintComponent(Graphics g) {
g.setColor(Color.BLUE); //設定顏色為藍色
int startY = 90;
int startX =60;
int endY = 160;
int endX =180;
int size = 100;
int dy = endY - startY;
int dx = endX - startX;
if (Math.abs(dy) + Math.abs(dx) == 0) {
return;
}
int stepx, stepy;
if (dy < 0) {
dy = -dy;
stepy = -1;
} else {
stepy = 1;
}
if (dx < 0) {
dx = -dx;
stepx = -1;
} else {
stepx = 1;
}
dy <<= 1;
dx <<= 1;
// Fill the first pixel.
// g.fillRect(startX - size / 2, startY - size / 2, size, size);
if (dx > dy) {
int fraction = dy - (dx >> 1);
while (startX != endX) {
if (fraction >= 0) {
startY += stepy;
fraction -= dx;
}
startX += stepx;
fraction += dy;
System.out.println("=====x = xCenter - radius=111======" );
// Fill pixel
g.setColor(Color.yellow);
g.fillRect(startX - size / 2, startY - size / 2, size, size);
g.setColor(Color.black);
g.drawRect(startX - size / 2, startY - size / 2, 80, 80);
}
} else {
int fraction = dx - (dy >> 1);
while (startY != endY) {
if (fraction >= 0) {
startX += stepx;
fraction -= dy;
}
startY += stepy;
fraction += dx;
System.out.println("===startX= "+ j +"=======" + startX);
System.out.println("===startY= "+ j +"=======" + startY);
System.out.println("===size= "+ j +"=======" + size);
System.out.println("==size / 2= "+ j +"=======" + size / 2);
System.out.println("===startX - size / 2 "+ j +"=======" + (startX - size / 2));
System.out.println("==startY - size / 2= "+ j +"=======" + (startY - size / 2));
// Fill pixel
g.setColor(Color.yellow);
g.fillRect(startX - size / 2, startY - size / 2, size, size);
g.setColor(Color.black);
g.drawRect(startX - size / 2, startY - size / 2, 60, 35);
//}
}
}
}
第二種方式 :
class ArcsPanel extends JPanel {protected void paintComponent(Graphics g) {
public void drawLineW(Graphics g, int x1, int y1, int x2, int y2, int thickness) {
// g.setColor(_blueColor);
// g.setAlpha(0);
int dX = x2 - x1;
int dY = y2 - y1;
double lineLength = Math.sqrt(dX * dX + dY * dY);
double scale = (double) (thickness) / (2 * lineLength);
// The x,y increments from an endpoint needed to create a rectangle...
double ddx = -scale * (double) dY;
double ddy = scale * (double) dX;
ddx += (ddx > 0) ? 0.5 : -0.5;
ddy += (ddy > 0) ? 0.5 : -0.5;
int dx = (int) ddx;
int dy = (int) ddy;
// Now we can compute the corner points...
final int xPoints[] = new int[4];
final int yPoints[] = new int[4];
xPoints[0] = x1 + dx;
yPoints[0] = y1 + dy;
xPoints[1] = x1 - dx;
yPoints[1] = y1 - dy;
xPoints[2] = x2 - dx;
yPoints[2] = y2 - dy;
xPoints[3] = x2 + dx;
yPoints[3] = y2 + dy;
g.fillPolygon(xPoints, yPoints, 4);
}
}