tags:

views:

179

answers:

3

Hi, (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

+2  A: 

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

Galghamon
great! just what a noob like me needed :) thanks a lot
A: 

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

}
+1  A: 

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.

Nick Holt