2017-05-15 60 views
-2

問題,所以我試圖擴展當前加載並在屏幕上工作,儘管圖像佔據了比賽,我創建的整個窗口的圖像。與圖像比例

我有3類文件: -

的BufferedImage
戰鬥機
遊戲。

BufferedImageLoader類: -

import java.awt.image.BufferedImage; 
    import java.io.IOException; 

    import javax.imageio.ImageIO; 

    public class BufferedImageLoader { 

     private BufferedImage image; 

     public BufferedImage loadImage(String path) throws IOException{ 

      image = ImageIO.read(getClass().getResource(path)); 
      return image; 
     } 
    } 

渲染和的paintComponent是從遊戲類

private void render(){ 

    BufferStrategy bs = this.getBufferStrategy(); 

    if(bs == null){ 
     createBufferStrategy(3); 
     return; 
    } 

    paintComponent(bs); 

} 

public void paintComponent(BufferStrategy bs){ 

     //Graphics g) { 

    //AffineTransform at = AffineTransform.getTranslateInstance(100, 100); 
    //at.scale(0.5, 0.5); 
    Graphics g = bs.getDrawGraphics(); 

    //Graphics2D g2d = (Graphics2D) g; 

    //g2d.drawImage(fighter, (BufferedImageOp) at, getHeight(), getWidth()); 

    g.drawImage(fighter, 0, 0, getWidth(),getHeight(), this); 
    g.dispose(); 
    bs.show(); 
} 

這是戰士類的代碼: -

import java.awt.image.BufferedImage; 

public class Fighter { 



private BufferedImage fighter; 

public Fighter(BufferedImage image) 
{ 
    this.fighter = image; 

} 

public BufferedImage grabImage() 
{ 
    fighter.getHeight(); 
    fighter.getWidth(); 


    return fighter; 
} 

} 

我目前使用Graphics g,就像你從代碼中看到的那樣,但是使用Graphics2D會更好,這樣我就可以使用AffineTransform?以及如何更改代碼以實現此目的?還將該比例添加到圖像。

的鏈接圖片是在這裏: - http://prntscr.com/f89kfs

+0

規範化通常是昂貴的,並且如果可以的話,則應該縮放圖像需要使用它(和然後使用經縮放的實例)之前,對於[示例](http://stackoverflow.com/questions/11959758/java -maintaining縱橫比-的-JPanel的背景圖像/ 11959928#11959928)和[示例](http://stackoverflow.com/questions/14115950/quality-of-image-after-resize-very-low-爪哇/ 14116752#14116752)。我甚至可以考慮使用[imgscalr(https://github.com/rkalla/imgscalr)產生一些非常好的結果 – MadProgrammer

+0

*「我目前使用的圖形G作爲您可以從代碼中看到,但會使用在Graphics2D更好」 * - 由'BufferStrategy'返回的'Graphics'實例是'Graphics2D'的一個實例,並且可以安全地投射它。個人而言,我會使用它,因爲它提供了'Graphics'不具備的附加功能,但這就是我; – MadProgrammer

+0

@MadProgrammer我真的需要哪些部分?只是g.drawImage(img.getScaledInstance(newWidth,-1,Image.SCALE_SMOOTH),x,y,this);? –

回答

0

的問題的解決方案是使用的AffineTransform: -

public void paintComponent(BufferStrategy bs){ 

    if(bs == null){ 
     createBufferStrategy(3); 
     return; 
    } 


    AffineTransform at = AffineTransform.getTranslateInstance(250, 250); 
    at.scale(0.15, 0.15); 
    Graphics2D g2d = (Graphics2D) bs.getDrawGraphics(); 
    g2d.drawImage(this.fighter, at, this); 

    g2d.dispose(); 
    bs.show(); 
    //repaint(); 
} 

它縮放圖像,並把它放在你想要的位置。