【问题标题】:Java2D: Increase the line widthJava2D:增加线宽
【发布时间】:2011-02-19 20:04:59
【问题描述】:

我想增加 Line2D 的宽度。我找不到任何方法来做到这一点。我是否需要为此实际制作一个小矩形?

【问题讨论】:

    标签: java swing graphics java-2d


    【解决方案1】:

    Stroke是什么:

    BasicStroke 类定义了一组基本的渲染属性,用于 图形基元的轮廓,用 其 Stroke 属性设置为此的 Graphics2D 对象 基本笔画。

    https://docs.oracle.com/javase/7/docs/api/java/awt/BasicStroke.html

    注意Stroke 设置:

    Graphics2D g2 = (Graphics2D) g;
    g2.setStroke(new BasicStroke(10));
    

    正在设置线宽,因为BasicStroke(float width):

    使用指定的线宽以及 cap 和 join 样式的默认值构造一个实体 BasicStroke。

    而且,它还会影响其他方法,例如 Graphics2D.drawLine(int x1, int y1, int x2, int y2)Graphics2D.drawRect(int x, int y, int width, int height)

    使用轮廓Shape的Graphics2D接口的方法 由 Stroke 对象返回的包括 draw 和任何其他方法 是根据该方法实现的,例如drawLine,drawRect, drawRoundRect、drawOval、drawArc、drawPolyline 和 drawPolygon。

    【讨论】:

      【解决方案2】:

      您应该使用setStroke 来设置Graphics2D 对象的描边。

      http://www.java2s.com 的示例为您提供了一些代码示例。

      以下代码生成如下图像:

      import java.awt.*;
      import java.awt.geom.Line2D;
      import javax.swing.*;
      
      public class FrameTest {
          public static void main(String[] args) {
              JFrame jf = new JFrame("Demo");
              Container cp = jf.getContentPane();
              cp.add(new JComponent() {
                  public void paintComponent(Graphics g) {
                      Graphics2D g2 = (Graphics2D) g;
                      g2.setStroke(new BasicStroke(10));
                      g2.draw(new Line2D.Float(30, 20, 80, 90));
                  }
              });
              jf.setSize(300, 200);
              jf.setVisible(true);
          }
      }
      

      (注意setStroke 方法在Graphics 对象中不可用。您必须将其强制转换为Graphics2D 对象。)


      本帖已改写为文章here

      【讨论】:

      • 插图+1!另外,考虑g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
      猜你喜欢
      • 2012-03-31
      • 2017-11-09
      • 2011-02-27
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 2020-06-08
      • 1970-01-01
      • 2017-08-11
      相关资源
      最近更新 更多