使用按钮和 jpanel 调整图像大小

问题描述 投票:0回答:1

我正在尝试在您单击不同的按钮时在按钮上弹出蛋糕的图像

我正在处理的代码部分我只想调整按钮的大小

    if (e.getSource() == cake) {
        BufferedImage myPicture = null;
        try {
            myPicture = ImageIO.read(new File("cake.jpg"));
            myPicture.getScaledInstance(800, 500, Image.SCALE_DEFAULT);
            
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        JLabel picLabel = new JLabel(new ImageIcon(myPicture));
        cake.add(picLabel, BorderLayout.CENTER); 
    }

cake propoties

我尝试按所示缩放图像,并通过查看其他堆栈溢出和其他网站来完成其他操作,但它们都不起作用

java image button jpanel
1个回答
0
投票

就像@g00se提到的:

创建该图像的缩放版本。返回一个新的 Image 对象...

因此您需要将其值赋回给

myPicture
变量,如下所示:

myPicture = myPicture.getScaledInstance(800, 500, Image.SCALE_DEFAULT);

顺便说一句,这是缩放图片的好方法,但如果您愿意,使用

AffineTransform
会更快。这是我用于缩放图像的方法:

/**
  * Scales the given image by the specified ratio 
  * using the AffineTransform method.
  *
  * @param source the original BufferedImage to be scaled.
  * @param ratio  the scaling ratio. A ratio greater than 1 
  * enlarges the image, less than 1 shrinks the image.
  * @return a new BufferedImage that is a scaled version of
  * the original image.
  */
private BufferedImage scaleImageFast(BufferedImage source, double ratio) {
    BufferedImage bi = new BufferedImage(
            (int) (source.getWidth() * ratio),
            (int) (source.getHeight() * ratio),
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = bi.createGraphics();
    AffineTransform at = AffineTransform.getScaleInstance(ratio, ratio);
    g2d.drawRenderedImage(source, at);
    g2d.dispose();
    return bi;
}
© www.soinside.com 2019 - 2024. All rights reserved.