绘制点网格 [英] Drawing a dot grid
问题描述
我是图形编程的新手.我正在尝试创建一个允许您绘制有向图的程序.首先,我设法绘制了一组矩形(代表节点),并通过覆盖 Java 中的绘制方法实现了平移和缩放功能.
I'm new to graphics programming. I'm trying to create a program that allows you to draw directed graphs. For a start I have managed to draw a set of rectangles (representing the nodes) and have made pan and zoom capabilities by overriding the paint method in Java.
当节点不多时,这一切似乎都运行良好.我的问题是在尝试绘制点网格时.我一开始使用了一些简单的测试代码,它使用两个嵌套的 for 循环覆盖了一个点网格:
This all seems to work reasonably well while there aren't too many nodes. My problem is when it comes to trying to draw a dot grid. I used a simple bit of test code at first that overlayed a dot grid using two nested for loops:
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);
}
}
这允许我平移网格但不能缩放.然而,平移时的表现很糟糕!我已经做了很多搜索,但我觉得我一定遗漏了一些明显的东西,因为我找不到关于这个主题的任何东西.
This allows me to pan the grid but not zoom. However, the performance when panning is terrible! I've done a lot of searching but I feel that I must be missing something obvious because I can't find anything on the subject.
任何帮助或指示将不胜感激.
Any help or pointers would be greatly appreciated.
--斯蒂芬
推荐答案
对点网格使用 BufferedImage.初始化一次,以后只绘制图像而不是一遍遍地绘制网格.
Use a BufferedImage for the dot grid. Initialize it once and later only paint the image instead of drawing the grid over and over.
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
}
使用这个很容易实现缩放:
And zooming is easily achieved using this:
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
绘制到缩放后的Graphic中会导致线宽等比例变大
Drawing into the zoomed Graphics will lead to proportionally larger line width, etc.
这篇关于绘制点网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!