Question

I'm looking for a fast and easy way to plot arbitrarily colored pixels in an SWT Canvas. So far I'm using something like that:

// initialization:
GC gc = new GC(canvas);

// inside the drawing loop:
Color cc = new Color(display, r, g, b);
gc.setForeground(cc);
gc.drawPoint(x, y);
cc.dispose();

This is horribly horribly slow. it takes about a second and a half to fill a 300x300 canvas with pixels. I could create an image off-screen, set the pixels in it and then draw the image. This will be faster but I specifically want the gradual painting effect of plotting the image pixel by pixel on the canvas.

Was it helpful?

Solution

You could draw several offscreen images where you gradually fill the 300x300 area. This way you can control how fast the image should appear.

OTHER TIPS

I bet that what is killing performance is allocating and releasing 90,000 Color objects. Remember, in SWT, each Color object allocates native resources, which is why you have to dispose() it. This means each time you allocate and dispose a Color object, you have to transition from the JVM to native code and back.

Can you cache your Color instances while in the 300x300 pixel loop and then dispose of the objects after your loop? You'd need a somewhat intelligent cache that only holds a maximum of so many objects, and after that will dispose of some of its entries, but this should speed things up greatly.

Create a BufferedImage object:

BufferedImage bi = new new BufferedImage(300, 300, BufferedImage.TYPE_INT_RGB);

inside the drawing loop set your pixels:

bi.setRGB(x, y, int_rgb);
...

and finally display the buffered image:

g.drawImage(bi, 0, 0, null); 

If you find setRGB() slow, you can access the bitmap data directly:

int[] raster = ((DataBufferInt)bi.getRaster().getDataBuffer()).getData();

and later

raster[y * 300 + x] = int_rgb;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top