开发者

Flipping an image

I am creating a tile game where I need to flip images. With the code I have it produces this error:

Exception in thread "main" java.lang.IllegalArgumentException: Width (-1) and height (-1) cannot be &l开发者_开发知识库t;= 0

from this line:

Image newImage = gc.createCompatibleImage(
        image.getWidth(null),
        image.getHeight(null),
        Transparency.BITMASK);

here is the coding i have:

public Image getMirrorImage(Image image) {
    return getScaledImage(image, -1, 1);
}

private Image getScaledImage(Image image, float x, float y) {
    // set up the transform
    AffineTransform transform = new AffineTransform();
    transform.scale(x, y);
    transform.translate(
        (x-1) * image.getWidth(null) / 2,
        (y-1) * image.getHeight(null) / 2);

    // create a transparent (not translucent) image
    Image newImage = gc.createCompatibleImage(
        image.getWidth(null),
        image.getHeight(null),
        Transparency.BITMASK);

    // draw the transformed image
    Graphics2D g = (Graphics2D)newImage.getGraphics();
    g.drawImage(image, transform, null);
    g.dispose();

    return newImage;
}

Can anyone explain to me what i might need to do different or how i can make it work? Many thanks


It's possible for image.getWidth(null) and image.getHeight(null) to return -1 if they're not known yet. Image processing can be done concurrently and it might still be going when you try to call those methods (even locally it'll do this IIRC). Here's a snippet of code I've used before to wait for an image to be loaded before trying to access its width and height:

private void waitForImage(Image image) {
    Container container = new Container();
    MediaTracker tracker = new MediaTracker(container);
    tracker.addImage(image, 0);
    try {
        tracker.waitForID(0, 1000);
    } catch (Exception e) {
    }
}

I just tried a local test and the wait times were generally 1ms for some small images. It's not really any additional time, it just forces your code to wait for the last stage to complete to get the width and height.


The easiest way to flip the image is by negative scaling it. Example:

g2.drawImage(image, x, y, -width, height, null);

That will flip it vertically. This will flip it horizontally:

g2.drawImage(image, x, y, width, -height, null);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜