2008-10-06 66 views
0

有没有一种方法可以使用图形对象的'setClip()'方法来使用线条形状进行剪切?现在我试图使用一个多边形形状,但我有问题模拟线的“宽度”。我基本上划清界线,当我到达终点,我重新绘制,但这次是从y坐标减去线宽:Java2D:用线条剪切图形对象

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

它几乎工作,但该行的宽度变化基于其斜率。

我不能使用BrushStroke和drawLine()方法,因为一旦它传递一些任意的参考线,该线可以改变颜色。有没有我忽略的Shape的一些实现,或者我可以创建一个简单的实现,这会让我更容易做到这一点?

回答

1

如果有更好的方法,我从来没有碰过它。我能想到的最好的方法是使用一些三角函数来使线宽更加一致。

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

也许你可以使用Stroke.createClippedShape来做到这一点? (可能需要使用Area来添加从原始形状减去描边形状,具体取决于您正在尝试做什么。