0

When I attached a profiler (NetBeans) to my application, I found that half of the cpu time used by the paint mthod belonged to the drawLine(); method I use to draw a large grid across a large window (1000 by 650).

The grid has to be refreshed constantly, as I implemented panning as so:

/*
A simplified section of the MAIN class
*/
//size of grid squares
public static Dimension pixelgridsize = new Dimension(50,50);
//size in grid squares - initiated in main.
public static Dimension gridsize ;
//panning
public static double panx = 0;
public static double pany = 0;
@Override
public void paint(Graphics g2) {
    Graphics2D g = (Graphics2D)g2;
    Color thing = g.getColor();
    for(int i  = 0; i<gridsize.width;i++){
        if((i*pixelgridsize.width)>view.getX()&&
        (i*pixelgridsize.width)<view.x+view.width){
        g.drawLine((int)(i*pixelgridsize.width-panx), 0,(int)(i*pixelgridsize.width-panx), 700);}
    }
    for(int i  = 0; i<gridsize.height;i++){
        if((i*pixelgridsize.height)>view.getY()&&
    (i*pixelgridsize.height)<view.y+view.height){
        g.drawLine(0,(int)(i*pixelgridsize.height-pany), 1000, (int)(i*pixelgridsize.height-pany));}
    }
    g.setColor(thing);

Is there anyway to reduce cpu usage (drastically)?

*the view Rectangle is for use in panning, its the size of the window but 'ajusts' its position to accommodate the pan variables.

Nivetha T
  • 481
  • 1
  • 3
  • 17
  • Draw the grid to some kind of backing buffer (like a `BufferedImage`) and paint only the `BufferedImage`... – MadProgrammer Jan 29 '15 at 04:14
  • would that reduce cpu usage? – DarkWyvren Jan 29 '15 at 04:16
  • Yes, rendering an image significantly faster than performing multiple draw operations – MadProgrammer Jan 29 '15 at 04:18
  • And if you're using Swing, you really should be calling `super.paint` first... – MadProgrammer Jan 29 '15 at 04:19
  • Since your grid seems to be of fixed size (1000x700) might want to just store your grid in a BufferedImage and use g.drawImage. This is acheivable either by creating a file containing the image and then using ImageIO.read or just running your grid-drawing algorithm on a BufferedImage's createGraphics. In both cases, you'd want to set this image up the first time it is needed and just refer to it on future occasions. – k_g Jan 29 '15 at 04:19
  • You might then be able to take advantage of hardware optimization. See http://stackoverflow.com/questions/658059/graphics-drawimage-in-java-is-extremely-slow-on-some-computers-yet-much-faster for information on how to implement this option properly. – k_g Jan 29 '15 at 04:20

0 Answers0