在 Java 的 Canvas 上画东西

Draw things on Canvas in Java

我有一个 Entity 对象列表,我想在 canvas 上使用 Graphics2D 对象绘制所有这些对象,但是如果某些对象处于同一位置,则必须在其他对象之上绘制它们,我有一个解决方案像这样:

    for(Entity e : cloneEntities)
        if (e instanceof Dirty) e.render(g);
    for(Entity e : cloneEntities)
        if (e instanceof Box) e.render(g);
    for(Entity e : cloneEntities)
        if (e instanceof RunObstacle) e.render(g);

但它看起来很大。对于这种情况,有人有其他解决方案吗?提前致谢!

您可以按类型 cloneEntities 排序(您可能需要自定义比较器来指定顺序),然​​后按顺序呈现它们。这做同样的事情,但可能节省一些计算。

类似于@patrick-hainge 的回答,您可以在 Entity 中添加一个名为 z-indexint 类型的字段,该字段在 [=11= 的构造函数中设置].因此,您的子构造函数将需要向它发送一个值。

然后您只需在调用每个列表之前对 cloneEntities 列表进行排序,如下所示:

clonedEntities.stream().sort((a,b)->a.getZindex()-b.getZindex()).forEach((a)->a.render(g));

备注

这仅在 cloneEntities 声明为 List 而不是 Set

时有效

最好的解决方案可能是为正面、中间和背景创建一些 BufferedImages:

BufferedImage dirties = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Buffered Image boxes = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB)
BufferedImage obstacles = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

for(Entity e : cloneEntities){
    if (e instanceof Dirty) e.render(dirties.getGraphics());
    if (e instanceof Box) e.render(boxes.getGraphics());
    if (e instanceof RunObstacle) e.render(obstacles.getGraphics());
}
//And then render all Layers
 g.drawImage(dirties, 0, 0, width, height, null);
 g.drawImage(boxes, 0, 0, width, height, null);
 g.drawImage(obstacles, 0, 0, width, height, null);

此解决方案由 .