在运行时调整ImageIcon(或Image)的大小

时间:2013-10-03 18:40:10

标签: java image swing

我正在尝试使用线程在运行时定期增加imageIcon的高度和宽度。

我试过这个但没有成功

Image img = image.getImage();
BufferedImage bi = new BufferedImage(
            img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.createGraphics();
g.drawImage(img, 0, 0, 100, 100, null);
ImageIcon image = new ImageIcon(bi);
有人能帮帮我吗? THX

import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class ui {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        //set imageicon
        final ImageIcon image = new ImageIcon(
                "C:\\Users\\User\\workspace\\Project\\images\\c.png");
        JLabel imagelabel = new JLabel(image, JLabel.CENTER);
        frame.add(imagelabel);

        ScheduledExecutorService exec = Executors
                        .newSingleThreadScheduledExecutor();
        exec.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() { 
                // ---->How to increase height and width dynamically at runtime?    
            }
        }, 0, 500, TimeUnit.MILLISECONDS);
    }
}

1 个答案:

答案 0 :(得分:2)

在您加载图片时,只需在draw()的实施中paintComponent()。覆盖get\[Preferred|Maximum|Minimum\]Size()以定义初始大小并选择合适的布局来控制调整大小行为。使用AffineTransformOp控制插值类型,如here所示。另请考虑getScaledInstance(),检查herehere