0

Is there a way to use a Graphics object's 'setClip()' method to clip using a Line-ish shape? Right now I'm trying to use a Polygon shape but I'm having problems simulating the "width" of the line. I basically draw the line, and when I reach the end, I redraw it but this time subtract the line width from y-coordinate:

Polygon poly = new Polygon();

for(int i = 0; i < points.length; i++)
  poly.addPoint(points.[i].x, points.[i].y);

// Retrace line to add 'width'
for(int i = points.length - 1; i >=0; i--)
  poly.addPoint(points[i].x, points[i].y - lineHeight);

It almost works but the width of the line varies based upon its slope.

I can't use the BrushStroke and drawLine() methods because the line can change color once it passes some arbitrary reference line. Is there some implementation of Shape that I overlooked, or an easy one I can create, that will let me do this more easily?

4

3 回答 3

1

If there is a better way, I've never run across it. The best I can think of is to use some trigonometry to make the line width more consistent.

于 2008-10-06T20:59:55.380 回答
1

好的,我设法在不使用 setClip() 方法的情况下提出了一个非常好的解决方案。它涉及将我的背景绘制到一个中间 Graphics2D 对象,使用 setComposite() 来指定我想要如何屏蔽像素,然后在顶部使用 drawLine() 绘制我的线。一旦我有了这条线,我就通过 drawImage 将它重新绘制在我原来的 Graphics 对象之上。这是一个例子:

BufferedImage mask = g2d.getDeviceConfiguration().createCompatibleImage(width, height, BufferedImage.TRANSLUCENT);
Graphics2D maskGraphics = (Graphics2D) mask.getGraphics();
maskGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

maskGraphics.setStroke(new BasicStroke(lineWidth));
maskGraphics.setPaint(Color.BLACK);

// Draw line onto mask surface first.
Point prev = line.get(0);
for(int i = 1; i < line.size(); i++)
{
    Point current = line.get(i);
    maskGraphics.drawLine(prev.x, prev.y, current.x, current.y);
        prev = current;
}

// AlphaComposite.SrcIn:    "If pixels in the source and the destination overlap, only the source pixels
//                          in the overlapping area are rendered."
maskGraphics.setComposite(AlphaComposite.SrcIn);

maskGraphics.setPaint(top);
maskGraphics.fillRect(0, 0, width, referenceY);

maskGraphics.setPaint(bottom);
maskGraphics.fillRect(0, referenceY, width, height);

g2d.drawImage(mask, null, 0, 0);
maskGraphics.dispose();
于 2008-10-06T22:05:06.403 回答
0

也许您可以使用 Stroke.createClippedShape 来执行此操作?(可能需要使用区域从原始形状中减去描边形状,具体取决于您要执行的操作。

于 2011-02-14T17:32:31.657 回答