【问题标题】:Java2D: Clipping a Graphics object with a LineJava2D:用线条剪裁图形对象
【发布时间】:2011-02-15 01:32:31
【问题描述】:

有没有办法使用 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 实现,或者我可以创建的一个简单的实现,可以让我更轻松地做到这一点?

【问题讨论】:

    标签: java java-2d


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-01-14
          • 1970-01-01
          • 1970-01-01
          • 2013-11-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多