2015-06-09 77 views
0

我已經能夠使字體與組件的大小成比例,但是,我似乎無法弄清楚如何製作圖像縮放。我的程序工作的方式是將組件添加到arrayList中,然後在最後設置每個組件的邊界。我想這種變化和一直無法得到它的工作:調整圖像的大小以縮小它在/標籤中的面板

public class ImagePanel extends JPanel implements Updater{ 
    BufferedImage resizer; 
    private int width; 
    private int height; 
    private JLabel picLabel; 
    private BufferedImage myPicture; 
    /** 
    * Searches for the image in the specified location and sets the background of the ImagePanel to the specified color. 
    * @param location 
    * @param bGColor 
    */ 
    public ImagePanel(String location, Color bGColor) 
    { 

     myPicture = null; 
     this.setLayout(new BorderLayout()); 
     try { 
      // TODO make it use the string. 
      myPicture = ImageIO.read(new File("images/logo-actavis.png")); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     picLabel = new JLabel(new ImageIcon(myPicture)); 
     add(picLabel,BorderLayout.CENTER); 
     this.addComponentListener(new ComponentAdapter() { 
       @Override 
       /** 
       * Makes it so it does not stretch out text. Resizes the fonts to scale with the screen width.. 
       */ 
       public void componentResized(ComponentEvent e) { 
        if(picLabel.getHeight()!=0&&picLabel.getWidth()!=0) 
        { 
         width = picLabel.getWidth(); 
         height = picLabel.getHeight(); 
         myPicture=resize(myPicture, width, height); 
        } 

       } 
      }); 


     this.setBackground(bGColor); 
    } 
    public static BufferedImage resize(BufferedImage image, int width, int height) { 
     BufferedImage bi = new BufferedImage(width, height, BufferedImage.TRANSLUCENT); 
     Graphics2D g2d = (Graphics2D) bi.createGraphics(); 
     g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY)); 
     g2d.drawImage(image, 0, 0, width, height, null); 
     g2d.dispose(); 
     return bi; 
    } 
} 

回答

1

您可以使用該方法來獲得縮放後的圖像從原來的一個

public Image getScaledInstance(int width, int height, int hints)

1

而不是使用一個ImageIcon。你可以使用Darryl's Stretch Icon

圖標將根據標籤可用的空間自動縮放。您可以按比例縮放圖像,或者讓圖像填充整個空間。

0

落得這樣做的:

 this.addComponentListener(new ComponentAdapter() { 
      @Override 
      /** 
      * Makes it so it does not stretch out text. Resizes the fonts to scale with the screen width.. 
      */ 
      public void componentResized(ComponentEvent e) { 
       Double width = (double) e.getComponent().getWidth(); 
       Double height = (double) e.getComponent().getHeight(); 
       double scalingFactor=Math.min(width/originalWidth, height/originalHeight)*.7; 
       myPicture = myPicture.getScaledInstance((int)(originalWidth*(scalingFactor)),(int) (originalHeight*(scalingFactor)), Image.SCALE_SMOOTH); 
       picLabel = new JLabel(new ImageIcon(myPicture)); 
       add(picLabel,BorderLayout.CENTER); 

      } 
    }); 

當原來的高度/寬度是原始圖像的縱橫比。我將scalingFactor乘以.7,因爲我不希望它填滿整個Panel。

相關問題