歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java Swing的背景圖片按比例縮放

Java Swing的背景圖片按比例縮放

日期:2017/3/1 10:19:22   编辑:Linux編程

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. public class ScaleIcon implements Icon {
  8. private BufferedImage i = null;
  9. private Icon icon = null;
  10. public ScaleIcon(Icon icon) {
  11. this.icon = icon;
  12. }
  13. @Override
  14. public int getIconHeight() {
  15. return icon.getIconHeight();
  16. }
  17. @Override
  18. public int getIconWidth() {
  19. return icon.getIconWidth();
  20. }
  21. public void paintIcon(Component c, Graphics g, int x, int y) {
  22. float wid = c.getWidth();
  23. float hei = c.getHeight();
  24. int iconWid = icon.getIconWidth();
  25. int iconHei = icon.getIconHeight();
  26. Graphics2D g2d = (Graphics2D) g;
  27. g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
  28. g2d.scale(wid / iconWid, hei / iconHei);
  29. icon.paintIcon(c, g2d, 0, 0);
  30. }
  31. public static void main(String[] args) {
  32. ScaleIcon icon = new ScaleIcon(new ImageIcon(ClassLoader.getSystemResource("img/main.jpg")));
  33. JLabel label = new JLabel(icon);
  34. JFrame frame = new JFrame();
  35. frame.getContentPane().add(label, BorderLayout.CENTER);
  36. // frame.getContentPane().add(new JButton("click"),BorderLayout.NORTH);
  37. frame.setSize(800, 600);
  38. frame.setLocationRelativeTo(null);
  39. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  40. frame.setVisible(true);
  41. }
  42. }

Copyright © Linux教程網 All Rights Reserved