user143602
user143602

Reputation: 15

java graphics - a shape with two colours

(this is java) I have an oval, representing a unit. I want the colour of the oval to represent the unit's health. So a perfectly healthy unit will be all green. and with the unit's health decreasing the oval starts filling with red from the bottom. so, on 50% health the oval would be red in bottom half and green in the top half, and fully red when the unit's dead. I'm sure the solution here must be obvious and trivial , but I just can't see it. thanks a lot

Upvotes: 0

Views: 1334

Answers (3)

Nick Holt
Nick Holt

Reputation: 34311

Override the paint method something like this:

public void paint(Graphics graphics) 
{    
  super.paint(graphics);

  Rectangle originalClipBounds = graphics.getClipBounds();

  try
  {
    graphics.clipRect(100, 100, 100, 25);
    graphics.setColor(Color.RED);
    graphics.fillOval(100, 100, 100, 100);
  }
  finally
  {
    graphics.setClip(originalClipBounds);
  }

  try
  {
    graphics.clipRect(100, 125, 100, 75);
    graphics.setColor(Color.BLUE);
    graphics.fillOval(100, 100, 100, 100);
  }
  finally
  {
    graphics.setClip(originalClipBounds);
  }
}

Might want to enhance it with some double buffering but you get the gist.

Upvotes: 1

user101884
user101884

Reputation: 717

You can set the clip on the graphics when you draw the green. Only things within the clip actually get painted.

    public void paint(Graphics g) {
    super.paint(g);
    Graphics2D g2d = (Graphics2D)g.create();

    g2d.setColor(Color.RED);
    g2d.fillOval(10, 10, 200, 100);

    g2d.setColor(Color.GREEN);
    g2d.setClip(10, 10, 200, 50); 
    g2d.fillOval(10, 10, 200, 100);

}

Upvotes: 0

Galghamon
Galghamon

Reputation: 2042

You can draw a red oval in the background, then draw a green intersection of an oval and a rectangle, where the rectangle starts below the oval, then moves further to the top to reveal more of the red oval beneath.

You might like to read up on how to construct complex shapes out of primitives here

Upvotes: 2

Related Questions