tset0401
tset0401

Reputation: 25

Draw things on Canvas in Java

I have a list of Entity object, I want to draw all of them using Graphics2D object on a canvas but some objects must be drawn over others if they are at the same position, I have one solution like this:

    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);

but it's seem like massive. Anyone have other solution for this situation? thanks in advance!

Upvotes: 1

Views: 301

Answers (3)

qry
qry

Reputation: 457

Probably the best solution is to create a few BufferedImages for Front, Middle and Background:

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);

This solution is by Multiple independent layers in Graphics.

Upvotes: 0

CraigR8806
CraigR8806

Reputation: 1584

Similar to @patrick-hainge 's answer, you could add a field in Entity called z-index of type int that gets set in the constructor of Entity. Therefore, your child constructor would be required to send it a value.

Then you would just sort the cloneEntities list before calling render on each like so:

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

Note

This will only work if cloneEntities is declared as a List and not a Set

Upvotes: 0

user7953532
user7953532

Reputation:

You could sort cloneEntities by type (you might need a custom Comparator to specify ordering) and then render them all in order. This does much the same thing but might save some computations.

Upvotes: 1

Related Questions