【问题标题】:Drawing dashed line in java在java中绘制虚线
【发布时间】:2021-11-16 21:21:09
【问题描述】:

我的问题是我想在面板中画一条虚线。我可以做到,但它也用虚线画了我的边框。

有人能解释一下原因吗?我正在使用paintComponent进行绘制并直接绘制到面板上。

这是绘制虚线的代码:

public void drawDashedLine(Graphics g, int x1, int y1, int x2, int y2){
        Graphics2D g2d = (Graphics2D) g;
        //float dash[] = {10.0f};
        Stroke dashed = new BasicStroke(3, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[]{9}, 0);
        g2d.setStroke(dashed);
        g2d.drawLine(x1, y1, x2, y2);
    }

【问题讨论】:

    标签: java graphics


    【解决方案1】:

    您正在修改传递给paintComponent() 的Graphics 实例,该实例也用于绘制边框。

    相反,复制Graphics 实例并使用它来绘制:

    public void drawDashedLine(Graphics g, int x1, int y1, int x2, int y2){
    
      // Create a copy of the Graphics instance
      Graphics2D g2d = (Graphics2D) g.create();
    
      // Set the stroke of the copy, not the original 
      Stroke dashed = new BasicStroke(3, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL,
                                      0, new float[]{9}, 0);
      g2d.setStroke(dashed);
    
      // Draw to the copy
      g2d.drawLine(x1, y1, x2, y2);
    
      // Get rid of the copy
      g2d.dispose();
    }
    

    【讨论】:

    • 我有一个简单的问题:在什么情况下我必须克隆当前的图形?显然不需要克隆每个图形实例:)
    • 任何时候修改 Graphics 对象。像颜色这样的设置可能会被其他绘画方法再次设置,但像描边这样的设置并不总是被重置。它甚至可能在不同的外观和感觉之间有所不同,所以安全总比后悔好。
    【解决方案2】:

    另一种可能性是存储交换局部变量中使用的值(例如 Color , Stroke 等...)并将它们设置回使用图形。

    类似:

    Color original = g.getColor();
    g.setColor( // your color //);
    
    // your drawings stuff
    
    g.setColor(original);
    

    这适用于您决定对图形进行的任何更改。

    【讨论】:

      【解决方案3】:

      您通过设置描边修改了图形上下文,随后的方法(例如paintBorder())使用相同的上下文,因此继承了您所做的所有修改。

      解决方案: 克隆上下文,将其用于绘画并在之后处理它。

      代码:

      // derive your own context  
      Graphics2D g2d = (Graphics2D) g.create();
      // use context for painting
      ...
      // when done: dispose your context
      g2d.dispose();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-08-15
        • 1970-01-01
        • 2017-12-21
        • 2017-07-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多