无法用Java2D绘制细线 [英] Can't draw thin lines with Java2D

查看:141
本文介绍了无法用Java2D绘制细线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试绘制一个1像素笔划的多边形。因为整个多边形按100缩放,我将线宽设置为0.01。但是出于某种原因,多边形被绘制的屏幕线宽看起来是100像素而不是1。

I'm trying to draw a polygon with a stroke of 1 pixel. Because the entire polygon is scaled by 100, I set the line width to 0.01. For some reason though, the polygon gets drawn with an on-screen line width of what looks to be 100 pixels instead of 1.

我正在使用 GeneralPath 作为多边形形状。如果我使用相同的方法绘制 Line2D 形状,则会绘制细线。

I'm using GeneralPath as the polygon shape. Thin lines do get drawn if I use the same approach for drawing Line2D shapes.

g2d.scale(100, 100);
g2d.setStroke(new BasicStroke(0.01f));
g2d.draw(theShape);






新信息:如果我删除了setStroke行,我正确得到一个2像素的行,因为之前在Graphics2D对象上设置了一个0.02f的BasicStroke。


New info: If I remove the setStroke line I correctly get a 2 pixel line, since a BasicStroke of 0.02f was set on the Graphics2D object earlier.

这是真正的setStroke行

This is the real setStroke line

g.setStroke(new BasicStroke((float) (1f / getRoot().scaleX)));


推荐答案

以下代码生成如下输出。您的代码中的其他位置必须有错误。也许您在问题中省略了对 scale 的另一个调用:

The following code produces the output show below. You must have an error elsewhere in your code. Perhaps another call to scale that you have omitted in your question:

import java.awt.*;

public class FrameTest {
    public static void main(String[] args) throws InterruptedException {

        JFrame f = new JFrame("Demo");
        f.getContentPane().setLayout(new BorderLayout());    
        f.add(new JComponent() {
            public void paintComponent(Graphics g) { 
                Graphics2D g2d = (Graphics2D) g;

                GeneralPath theShape = new GeneralPath();
                theShape.moveTo(0, 0);
                theShape.lineTo(2, 1);
                theShape.lineTo(1, 0);
                theShape.closePath();

                g2d.scale(100, 100);
                g2d.setStroke(new BasicStroke(0.01f));
                g2d.draw(theShape);
            }
        });

        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(300, 300);
        f.setVisible(true);
    }
}

这篇关于无法用Java2D绘制细线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆