gpt4 book ai didi

java - 绘制点网格

转载 作者:行者123 更新时间:2023-11-29 04:04:15 25 4
gpt4 key购买 nike

我是图形编程新手。我正在尝试创建一个允许您绘制有向图的程序。一开始,我设法绘制了一组矩形(代表节点),并通过覆盖 Java 中的 paint 方法实现了平移和缩放功能。

这一切似乎在没有太多节点的情况下工作得相当好。我的问题是在尝试绘制点网格时。我首先使用了一些简单的测试代码,它使用两个嵌套的 for 循环覆盖了一个点网格:

int iPanX = (int) panX;
int iPanY = (int) panY;
int a = this.figure.getWidth() - iPanX;
int b = this.figure.getHeight() - (int) iPanY;

for (int i = -iPanX; i < a; i += 10) {
for (int j = -iPanY; j < b; j += 10) {
g.drawLine(i, j, i, j);
}
}

这允许我平移网格但不能缩放。但是,平移时的性能非常糟糕!我做了很多搜索,但我觉得我一定遗漏了一些明显的东西,因为我找不到关于这个主题的任何东西。

如有任何帮助或指点,我们将不胜感激。

--斯蒂芬

最佳答案

为点网格使用 BufferedImage。初始化一次,以后只绘制图像而不是一遍又一遍地绘制网格。

private init(){
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
// then draw your grid into g
}

public void paint(Graphics g) {
g.drawImage(image, 0, 0, null);
// then draw the graphs
}

使用这个很容易实现缩放:

g.drawImage(image, 0, 0, null); // so you paint the grid at a 1:1 resolution
Graphics2D g2 = (Graphics2D) g;
g2.scale(zoom, zoom);
// then draw the rest into g2 instead of g

绘制成缩放后的图形会导致线宽等比例变大

关于java - 绘制点网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1237759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com