我可以画线,但是厚度是恒定的。按下按钮时需要更改厚度。在此示例中,按“ w”将增加厚度,按“ q”将减小厚度。
import java.awt.*;
import java.applet.*;
import sun.swing.SwingUtilities2;
public class draw extends Applet {
boolean isBlack = true;
Point startPoint;
Point points[];
int numPoints;
boolean drawing;
int n = 0;
@Override
public void init() {
startPoint = new Point(0, 0);
points = new Point[10000];
drawing = false;
resize(300, 400);
}
@Override
public void paint(Graphics g) {
if (n == 0) {
g.setColor(Color.red);
}
if (n == 1) {
g.setColor(Color.green);
}
if (n == 2) {
g.setColor(Color.blue);
}
if (n == 3) {
g.setColor(Color.black);
}
int oldX = startPoint.x;
int oldY = startPoint.y;
for (int i = 0; i < numPoints; ++i) {
g.drawLine(oldX, oldY, points[i].x, points[i].y);
oldX = points[i].x;
oldY = points[i].y;
}
}
@Override
public boolean keyDown(Event evt, int key) {
char keyChar = (char) key;
if (keyChar == 'w') {
n++;
if (n > 3) {
n = 0;
}
}
if (keyChar == 'q') {
n--;
if (n < 0) {
n = 3;
}
}
return true;
}
@Override
public boolean mouseDown(Event evt, int x, int y) {
if (!drawing) {
startPoint.x = x;
startPoint.y = y;
}
drawing = !drawing;
return true;
}
@Override
public boolean mouseMove(Event evt, int x, int y) {
if ((drawing) && (numPoints < 10000)) {
points[numPoints] = new Point(x, y);
++numPoints;
repaint();
}
return true;
}
}
但是我无法计算线的粗细,我该怎么做?
最佳答案
您需要使用Graphics2D软件包:
Graphics2D g2 = SwingUtilities2.getGraphics2D(g);
g2.setStroke(new BasicStroke(n));
g2.drawLine(oldX, oldY, points[i].x, points[i].y);
我认为这就是您所需要的。自从我使用它已经有一段时间了。
关于java - 绘制时计算线条粗细,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32603259/