2013-10-26 72 views
0

我很新的图形在Java中,我试图创建一个形状,剪辑到另一个形状的底部。下面是我想要达到一个例子:2D剪辑区域的形状

http://i.stack.imgur.com/g3jKJ.png

凡在形状底座上的白线是何许圆形边缘之内; 我这样做目前的办法是,像这样:

g2.setColor(gray); 
Shape shape = getShape(); //round rectangle 
g2.fill(shape); 
Rectangle rect = new Rectangle(shape.getBounds().x, shape.getBounds().y, width, height - 3); 
Area area = new Area(shape); 
area.subtract(new Area(rect)); 
g2.setColor(white); 
g2.fill(area); 

我仍然与剪辑方法进行实验,但我似乎无法得到它的权利。目前的方法是否正确(性能明智,因为组件经常重新绘制)还是有更高效的方法?

+1

发布您的[SSCCE](http://sscce.org/),证明问题。 – camickr

+0

我怀疑更有效的方法是首先对白色和黄色进行加强,而不是进行区域减法,然而对Area进行少量(可能是昂贵的)操作的话,您仍然在使用相同数量的paintcalls。 – arynaq

+1

让效率更高的唯一方法是将结果缓冲到BufferedImage上,并简单地绘制,只根据需要更改缓冲区... – MadProgrammer

回答

1

这是当前的方法确定(性能明智的,因为该组件重画经常)..

减去形状是我怎么会去了解它。对象可以是几个实例,或者(可能)是根据需要为transformed的单个实例。

  1. A text demo.,使用缩放&衰落。
  2. 这是one with simple lines(..和点,..它是动画)。

当然,如果图像是纯添加剂,使用BufferedImage作为画布&显示它在一个JLabel/ImageIcon组合。就像在这两个例子中一样。

1

我认为你关于使用剪辑方法的最初想法是正确的做法。这适用于我:

static void drawShapes(Graphics2D g, int width, int height, 
    Shape clipShape) { 

    g.setPaint(Color.BLACK); 
    g.fillRect(0, 0, width, height); 

    g.clip(clipShape); 

    int centerX = width/2; 
    g.setPaint(new GradientPaint(
     centerX, 0, Color.WHITE, 
     centerX, height, new Color(255, 204, 0))); 

    g.fillRect(0, 0, width, height); 

    g.setPaint(Color.WHITE); 
    int whiteRectHeight = height * 4/5; 
    g.fillRect(0, whiteRectHeight, 
     width, height - whiteRectHeight); 
}