簡體   English   中英

Java:如何用導入的PNG文件替換“橢圓形”或“矩形”圖形?

[英]Java: How do I replace an “oval” or “rectangle” graphic with an imported PNG file?

我導入了:

 import javax.swing.ImageIcon;

我用這段代碼導入了PNG文件。 (我知道我可以輕松地創建一個黑色正方形,但這是將任何圖像導入到我想要的游戲中)。

Image player1 = Toolkit.getDefaultToolkit().createImage("Users/Documents/JavaGameImages/Tag/BlackSquare.png");

我試圖稍后再調用此圖像,但該圖像未出現在窗口中。 (假設myX = 100而myY = 100)

public void paint(Graphics g) {         
        g.setColor(BackgroundColor);
        g.fillRect(WindowWidth, WindowHeight, 1000, 1000);

//////////////////////以下代碼是我遇到麻煩的地方:

        g.drawImage(player1, myX, myY, null);

在構建用於分發的代碼時,您可能希望將圖像與類文件一起放入jar文件。 我要做的是將其放入與正在訪問它的類相同的目錄中,然后使用getClass()。getResource(fileName)對其進行訪問,如帶紋理背景邊框的以下代碼片段所示:

final Toolkit toolKit  = Toolkit.getDefaultToolkit();
URL imgURL = getClass().getResource(textureFileName);
if (imgURL != null)
{
  Image tmpImage = toolKit.createImage(imgURL);
  toolKit.prepareImage(tmpImage, -1, -1, 
            new ImageObserver() {
    public boolean imageUpdate(Image updatedImage, int infoFlags, int x, 
                               int y, int width, int height)
    {
      if ((infoFlags & ImageObserver.ALLBITS) == ImageObserver.ALLBITS)
      {
        int           w               = updatedImage.getWidth(null);
        int           h               = updatedImage.getHeight(null);
        BufferedImage backgroundImage = new BufferedImage(w, h, 
                                            BufferedImage.TYPE_INT_ARGB_PRE);
        Graphics2D    g = backgroundImage.createGraphics();
        g.drawImage(updatedImage, 0, 0, null);
        g.dispose();

        Rectangle rect = new Rectangle(0, 0, w, h);
        texture = new TexturePaint(backgroundImage, rect);

        return false;
      }

      return true;
    }
  });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM