繁体   English   中英

Java2D:使用Line剪切图形对象

[英]Java2D: Clipping a Graphics object with a Line

有没有一种方法可以使用Graphics对象的'setClip()'方法来裁剪呈Line形状的图形? 现在,我正在尝试使用多边形形状,但是在模拟线的“宽度”时遇到了问题。 我基本上画了线,到达终点时,我重新画了线,但是这次从y坐标减去线宽:

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实施,或者我可以创建的简单实施,可以让我更轻松地完成此操作?

如果有更好的方法,我永远不会遇到它。 我能想到的最好的方法是使用三角函数使线宽更一致。

好的,我设法不使用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();

也许您可以使用Stroke.createClippedShape来做到这一点? (可能需要使用Area来添加/减去原始形状的笔触形状,具体取决于您要尝试执行的操作。

暂无
暂无

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

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