当前位置: 技术问答>java相关
用java.awt.Graphics画线,能否设定线的宽幅?
来源: 互联网 发布时间:2014-12-23
本文导语: 用java.awt.Graphics画线,能否设定线的宽幅 | 是这样吗! public void drawThickLine( Graphics g, int x1, int y1, int x2, int y2, int thickness, Color c) { // The thick line is in fact a filled polygon g....
用java.awt.Graphics画线,能否设定线的宽幅
|
是这样吗!
public void drawThickLine(
Graphics g, int x1, int y1, int x2, int y2, int thickness, Color c) {
// The thick line is in fact a filled polygon
g.setColor(c);
int dX = x2 - x1;
int dY = y2 - y1;
// line length
double lineLength = Math.sqrt(dX * dX + dY * dY);
double scale = (double)(thickness) / (2 * lineLength);
// The x and 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...
int xPoints[] = new int[4];
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);
}
public void drawThickLine(
Graphics g, int x1, int y1, int x2, int y2, int thickness, Color c) {
// The thick line is in fact a filled polygon
g.setColor(c);
int dX = x2 - x1;
int dY = y2 - y1;
// line length
double lineLength = Math.sqrt(dX * dX + dY * dY);
double scale = (double)(thickness) / (2 * lineLength);
// The x and 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...
int xPoints[] = new int[4];
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);
}
|
在你的画线程序中加
paint(Graphics g)
{
Graphics2D g2D = (Graphics2D) g;
g2D.setStroke(new BasicStroke(width));//width 是你要的线的宽度。
}
paint(Graphics g)
{
Graphics2D g2D = (Graphics2D) g;
g2D.setStroke(new BasicStroke(width));//width 是你要的线的宽度。
}
|
还有,你的jdk是什么版本的?
|
没有办法,需要使用jdk2的java.awt.Graphcs2d