2008-10-06 64 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來添加從原始形狀減去描邊形狀,具體取決於您正在嘗試做什麼。