tags:

views:

263

answers:

2

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.

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.

--Stephen

+1  A: 

I think re-drawing all your dots every time the mouse moves is going to give you performance problems. Perhaps you should look into taking a snapshot of the view as a bitmap and panning that around, redrawing the view 'properly' when the user releases the mouse button?

Chris Roberts
+1  A: 

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

Drawing into the zoomed Graphics will lead to proportionally larger line width, etc.

Stroboskop
Thanks, performance has increased massively! There are a few quirks that I'll have to iron out but overall it is much improved.The solution you offer for zooming isn't ideal as this increases the size of the grid which I would prefer to keep as single pixels. Do I update the grid img on a zoom to accomodate?
SRoe
yeah, that occurred to me afterwards. It depends on how often you expect the zoom to change. I think you should update the grid image with every zoom change. And in paint(g) you could draw the grid at a 1:1 zoom and then set the scaling factor for the rest of the objects to paint. I think i'm going to update that in my answer.
Stroboskop