简体   繁体   English

Java图形-具有两种颜色的形状

[英]java graphics - a shape with two colours

(this is java) I have an oval, representing a unit. (这是java)我有一个椭圆形,代表一个单位。 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. 因此,在有50%生命值的情况下,椭圆形的下半部分将为红色,而上半部分将为绿色,当设备死了时,该椭圆将为全红色。 I'm sure the solution here must be obvious and trivial , but I just can't see it. 我敢肯定,这里的解决方案一定是显而易见且微不足道的,但我只是看不到它。 thanks a lot 非常感谢

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 你可能会喜欢上阅读了如何构建复杂形状出来的原语在这里

Override the paint method something like this: 覆盖paint方法,如下所示:

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. 可能希望通过一些双重缓冲来增强它,但是您的主旨是。

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM