Java Swing的背景图片按比例缩放


Java Swing的背景图片按比例缩放

  1. import java.awt.*;  
  2. import java.awt.image.BufferedImage;  
  3. import javax.swing.Icon;  
  4. import javax.swing.ImageIcon;  
  5. import javax.swing.JFrame;  
  6. import javax.swing.JLabel;  
  7.   
  8. public class ScaleIcon implements Icon {  
  9.   
  10.     private BufferedImage i = null;  
  11.     private Icon icon = null;  
  12.   
  13.     public ScaleIcon(Icon icon) {  
  14.         this.icon = icon;  
  15.     }  
  16.   
  17.     @Override  
  18.     public int getIconHeight() {  
  19.         return icon.getIconHeight();  
  20.     }  
  21.   
  22.     @Override  
  23.     public int getIconWidth() {  
  24.         return icon.getIconWidth();  
  25.     }  
  26.   
  27.     public void paintIcon(Component c, Graphics g, int x, int y) {  
  28.         float wid = c.getWidth();  
  29.         float hei = c.getHeight();  
  30.         int iconWid = icon.getIconWidth();  
  31.         int iconHei = icon.getIconHeight();  
  32.   
  33.         Graphics2D g2d = (Graphics2D) g;  
  34.         g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);  
  35.         g2d.scale(wid / iconWid, hei / iconHei);  
  36.         icon.paintIcon(c, g2d, 00);  
  37.     }  
  38.   
  39.     public static void main(String[] args) {  
  40.         ScaleIcon icon = new ScaleIcon(new ImageIcon(ClassLoader.getSystemResource("img/main.jpg")));  
  41.         JLabel label = new JLabel(icon);  
  42.         JFrame frame = new JFrame();  
  43.         frame.getContentPane().add(label, BorderLayout.CENTER);  
  44. //                frame.getContentPane().add(new JButton("click"),BorderLayout.NORTH);   
  45.         frame.setSize(800600);  
  46.         frame.setLocationRelativeTo(null);  
  47.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  48.         frame.setVisible(true);  
  49.     }  
  50. }  

相关内容