如何在libGDX中显示图片?

时间:2017-11-06 09:16:24

标签: java libgdx actor scene2d

我正在开发一款游戏,其中目录中的多张图片显示在屏幕上。 我正在使用scene2d。 但由于某些原因,这些图片不会显示在屏幕上 有谁能解释为什么? 这是我的代码:

public class Picture extends Actor {
    private Image img;
    public Picture(Image img) {
        this.img = img;
    }
}

应该绘制图片的游戏类别:

public class GameScreen extends Stage implements Screen {
     private FileHandle dirWithTextures;

public GameScreen() {
     super(new StretchViewport(1260.0f, 836.0f, new OrthographicCamera()));
     dirWithTextures = Gdx.files.internal("textures/");
}
public void buildStage() {
    ArrayList<Picture> pictureList = new ArrayList<Picture>();

    for (int i = 0; i < 4; i++) {
        pictureList.add(new Picture(new Image(newTexture(dirWithTextures.list()[i]))));
    }
    Collections.shuffle(pictureList);

    for (Picture p: pictureList) {
        p.setPosition(getWidth() / 2, getHeight() / 2, Align.center);
        addActor(p);
    }
  }
}

2 个答案:

答案 0 :(得分:1)

你没有覆盖Actor的draw()方法,所以Picture什么都没画。

像这样覆盖:

public class Picture extends Actor {
     private Image img;
     public Picture(Image img) {
         this.img = img;
     }
     @Overrine 
     public void draw(Batch batch, float parentAlpha){
         image.draw(batch, parentAlpha);
     }
}

演员绘制方法:

public void draw (Batch batch, float parentAlpha) {
}

答案 1 :(得分:1)

您的Picture班级是ActorDrawable部分与数据成员(Image)一样。

为什么你没有使用Image代替(Actor + Drawable)。

  

图像是可以绘制的Actor。

public class Picture extends Image {

      // Any additional data members
}

对于舞台,最好在这里使用关联关系而不是继承。

public class GameScreen implements Screen {
    private FileHandle dirWithTextures;
    private Stage stage;

  public GameScreen() {

      stage= new Stage(new StretchViewport(1260.0f, 836.0f, new OrthographicCamera()));
      dirWithTextures = Gdx.files.internal("textures/");
      buildStage();
  }

  public void buildStage() {
      ArrayList<Picture> pictureList = new ArrayList<Picture>();

      for (int i = 0; i < 4; i++) {
          pictureList.add(new Picture(new Texture(dirWithTextures.list()[i])));
      }
      Collections.shuffle(pictureList);

      for (Picture p: pictureList) {
         p.setPosition(100, 200, Align.center);  // < -- set Position according to your requirement.
         stage.addActor(p);
      }
  }

  @Override
  public void render(float delta) {

       Gdx.gl.glClearColor(0,0,0,1);
       Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

       stage.draw();
       stage.act();
  }

  // implement rest of method of Screen interface
}