Java2D : Clipping a Graphics object with a Line

标签 java java-2d

有没有办法使用 Graphics 对象的“setClip()”方法来使用 Line-ish 形状进行剪辑?现在我正在尝试使用多边形形状,但在模拟线条的“宽度”时遇到问题。我基本上画了这条线,当我到达终点时,我重新绘制它,但这次从 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();

关于Java2D : Clipping a Graphics object with a Line,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/176093/

相关文章:

java - Gradle:从测试源集中的主源集中覆盖类

java - 单条数据库记录插入失败是否需要回滚?

java - 通过扩展 Rectangle 类以使用其 contains 和 intersects 方法来实现碰撞检测

java - Scala:相当于 np.digitize 对数据进行分桶

java - 第三方 bundle 导入并使用系统 bundle 导出的任何版本的包

java - 在 Java 中渲染图像中的文本

java - java中的绘图框架

java - 如何使用 Graphics 对象 g 绘制透明形状?

java - 如何在Java中绘制绝对自定义的形状?

java - 使用 maven 和 IntelliJ 创建 apklibs