Fastest way to draw only a part of an image

I’m wondering what the fastest way to draw only a portion of an Image is. Right now I am using g.drawImage ( Image image, int sx1, int sy1, int sx2, int sy2, int dx1, int dy1, int dx2, int dy2, ImageObserver observer ). However, this function can also do scaling, so I’m not sure if it is optimized to deal with the case when no scaling has to be done.

The other way I know is to do g.setClip (…) and then g.drawImage(). But then I have create a compatible Graphics object from g, as to not screw up the original clipping area. I think that might slow things down…

Which way is faster?

from, Stefan

Okay, I’ve done some testing and figured out the fastest way to do it. Both the scaled drawImage() and g.create() are not the fastest. The best way to do it is:


paint (Graphics g)
{
Shape oldClip = g.getClip ();
g.setClip (x, y, width, height);
g.drawImage (sx, sy, x - sx, y - sy, null );
g.setClip (oldClip);
}

The cool thing about this approach is that if you have a loop that renders several pieces from different images, you can take the “Shape oldClip = g.getClip()” and “g.setClip (oldClip)” out of the loop and only call them once the loop is done, saving yourself some processor cycles.

from, Stefan

i seem to recall from an old thread of the previous board that setClip() creates garbage.
Can anyone confirm?

I hae used set clip to redraw various sprites on a game board and did not notice gc pauses due to excessive garbage collecton (and the game was running at 60fps adn there were about 5 set clips per frame).

-Chris