drawImage不起作用,但drawRect呢?

时间:2013-12-07 14:09:12

标签: java drawimage

这真的很奇怪......我正在关注我的游戏部分视频教程,当我使用时

package dashiesgame;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;

public class Cell extends Rectangle {
    private static final long serialVersionUID = 1L;
    public int[] id = {0,0};
    public Cell(Rectangle size, int[] id) {
        setBounds(size);
        this.id = id;
    }
public void render(Graphics g){
    g.setColor(new Color(255,100,100));
    g.fillRect(x,y,width,height);

}
}

它奏效了。我的屏幕底部有一些红色方块。我想用我在GIMP中创建并导出到png的单元格类型的东西替换红色平方,所以我用

替换了上面代码的结尾
 public void render(Graphics g){
    g.drawImage(Block.cell, x, y, width, height, null);

}

在视频中,这正是这个人所做的,而且效果很好。但是,它似乎并不适合我。我已经尝试将其更改为此而不是null,但它然后它使我实现ImageObserver,当我尝试运行代码时,这给了我很多错误。任何帮助将不胜感激!

另外,对不起,如果我对这件事有点无知......这是我第一次编码,我正在学习,所以请耐心等待......我还可以多给一些其他部分的代码,如果有人需要看到它,以帮助我弄清楚什么是错的....

这是定义Block.cell的地方:(它是类块,然后单元格是图像。我还拿出其他图像以节省空间,因为有一堆,但你明白了。)

package dashiesgame;

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

import javax.imageio.ImageIO;

public class Block {
    public static int tileSize = 20;
    public static int invLength = 6;
    public static int invCellSize = 40;
    public static int invCell = 8;
    public static int invCellSpace = 4;
    public static int invBorderSpace = 4;

    public static final int[] air1 = {-1, -1};
    public static final int[] TwilightBlock1 = {0,0};
    public static final int[] DashieBlock1 = {1,0};
    public static final int[] ApplejackBlock1 = {2,0};
    public static final int[] RarityBlock1 = {3,0};
    public static final int[] FluttershyBlock1 = {4,0};
    public static final int[] PinkieBlock1 = {5,0};


    public static BufferedImage cell ;
    {


    try {
        Block.cell = ImageIO.read(new File("cell.png"));
    } catch (IOException e) {
        e.printStackTrace();
    }
    }   
}

然后这[也很重要......

package dashiesgame;

import java.awt.Graphics;
import java.awt.Rectangle;

public class Inventory {
    public Cell[] invBar = new Cell[Block.invLength];
    public Inventory(){
        for (int i=0;i<invBar.length;i++){
            invBar[i] = new Cell(new Rectangle((Game.pixel.width / 2) - ((Block.invLength * (Block.invCellSize + Block.invCellSpace))/2) + (i * (Block.invCellSize + Block.invCellSpace)), Game.size.height - (Block.invCellSize + Block.invCellSpace), Block.invCellSize, Block.invCellSize), Block.air1 );
        }
    };
    public void render(Graphics g){
        for (int i=0;i<invBar.length;i++){
            invBar[i].render(g);
    }
}
}

1 个答案:

答案 0 :(得分:0)

与fillRect不同,

drawImage有一个奇怪的属性:它可能无法完成。如果它完成,它返回true。否则,它返回false,并且直到稍后调用paintComponent才完成绘图。

虽然这对大型图像来说不是线程安全的,但这里有一个解决方法:

while (!g.drawImage(...)) {
  // Loop body empty -- wait for drawImage to return true
}