调整图像大小不起作用

时间:2015-01-13 16:41:53

标签: java image-resizing

我做了一个Button类,它允许我有按钮(很明显)。但是在我的按钮类中,我正在使用图像来显示屏幕上的按钮。我得到了它的工作,但我想将图像调整到按钮的大小。

我的“Image Resizer”完美无缺,但是当我尝试调整按钮大小时,按钮不会显示。我没有任何错误。

这是我的Button类:

private String text;
private int size = 0;
private BufferedImage buttonHD;

public Button(int x, int y, int width, int height, int size) {
    super(x, y, width, height);
    this.size = size;
    buttonHD = Renderer.resizeImage(Images.button, x, y, width, height);
}

public Button setText(String text) {
    this.text = text;
    return this;
}

public void drawButton(Graphics g, int xoffset, int yoffset) {
    int xx = x + xoffset;
    int yy = y + yoffset;

    if(!MouseInput.MOUSE.intersects(this)) {
        g.drawImage(buttonHD, x, y, width, height, null);
    } else if(MouseInput.MOUSE.intersects(this)){
        g.setColor(Color.DARK_GRAY);
        g.fillRect(x, y, width, height);
    }

    Renderer.drawText(text, g, xoffset, yoffset, size);//Draws button text
}

我正在调整大小的原始图像存储在我的Images类中:

public static BufferedImage button;

这是我的“Button Resizer”方法:

public static BufferedImage resizeImage(BufferedImage origImg, int x, int y, int initWidth, int initHeight) {
    BufferedImage resizedImg = new BufferedImage(initWidth, initHeight, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = resizedImg.createGraphics();
    g2d.drawImage(origImg, x, y, initWidth, initHeight, null);
    g2d.dispose();
    return resizedImg;
}

我使用这些按钮的方式是ScreenState类。每个类代表每个州。按钮在那里设置,并由类的构造函数加载。

按钮可以正常工作,但图像不会显示。如果需要更多代码,请告诉我,我会为您提供。

我一直在努力解决这个问题,但没有运气。如果有人可以提示我的问题在哪里或者可能有解决方案,那就太好了。谢谢!

1 个答案:

答案 0 :(得分:1)

此功能会将BufferedImage的大小调整为给定的widthheight

public static BufferedImage resizeImage(BufferedImage image, int width, int height) {
    // calculate the scale factor
    double xScale = width / (double) image.getWidth();
    double yScale = height / (double) image.getHeight();
    // create the object that will contain the resized image
    BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    // resize the image
    Graphics2D g = (Graphics2D) resizedImage.getGraphics();
    g.scale(xScale, yScale);
    g.drawImage(image, 0, 0, null);
    g.dispose();
    // return the resized image
    return resizedImage;
}

然后只需使用它:

public class MyButton extends JButton
{
    private BufferedImage image;


    public MyButton() {
        image = resizeImage(ImageIO.read(IMAGE_PATH), BUTTON_WIDTH, BUTTON_HEIGHT);
    }


    @Override protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, null);
    }
}

IMAGE_PATH是您的图片所在的FileBUTTON_WIDTHBUTTON_HEIGHT是您的按钮尺寸。

相关问题