java swing的背景圖片按比例縮放

openkk 12年前發布 | 41K 次閱讀 Swing Java開發

import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class ScaleIcon implements Icon {

private BufferedImage i = null;
private Icon icon = null;

public ScaleIcon(Icon icon) {
    this.icon = icon;
}

@Override
public int getIconHeight() {
    return icon.getIconHeight();
}

@Override
public int getIconWidth() {
    return icon.getIconWidth();
}

public void paintIcon(Component c, Graphics g, int x, int y) {
    float wid = c.getWidth();
    float hei = c.getHeight();
    int iconWid = icon.getIconWidth();
    int iconHei = icon.getIconHeight();

    Graphics2D g2d = (Graphics2D) g;
    g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2d.scale(wid / iconWid, hei / iconHei);
    icon.paintIcon(c, g2d, 0, 0);
}

public static void main(String[] args) {
    ScaleIcon icon = new ScaleIcon(new ImageIcon(ClassLoader.getSystemResource("img/main.jpg")));
    JLabel label = new JLabel(icon);
    JFrame frame = new JFrame();
    frame.getContentPane().add(label, BorderLayout.CENTER);

// frame.getContentPane().add(new JButton("click"),BorderLayout.NORTH); frame.setSize(800, 600); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }</pre>java swing的背景圖片按比例縮放

轉自:http://blog.csdn.net/zhongweijian/article/details/7668926

 本文由用戶 openkk 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!