【问题标题】:Java Graphics 2D UI Arrow Head DirectionJava 图形 2D UI 箭头方向
【发布时间】:2010-10-18 17:39:11
【问题描述】:

我想使用图形填充多边形绘制箭头。但我的箭头在反面。任何的想法?

int xpoints[] = { 20, 30, 30, 35, 25, 15, 20 };
int ypoints[] = { 10, 10, 30, 30, 45, 30, 30 };
int npoints = 7;
g2D.fillPolygon(xpoints, ypoints, npoints);

【问题讨论】:

    标签: java polygon graphic


    【解决方案1】:

    Java 2D 坐标在用户空间中给出,其中左上角为 (0, 0)。见Coordinates

    当使用默认的从用户空间到设备空间的转换时,用户空间的原点是组件绘图区的左上角。 x坐标向右增加,y坐标向下增加,如下图所示。窗口的左上角是 0,0。所有坐标都使用整数指定,这通常就足够了。但是,某些情况下需要浮点甚至双精度,这也是受支持的。

    我找到了Java 2D - Affine Transform to invert y-axis,所以我将其修改为将原点翻译为左下角,并将其与您的箭头结合起来:

    protected  void paintComponent(Graphics g) {
        super.paintComponent(g);
    
        Graphics2D g2 = (Graphics2D) g;
    
        Insets insets = getInsets();
        // int w = getWidth() - insets.left - insets.right;
        int h = getHeight() - insets.top - insets.bottom;
    
        AffineTransform oldAT = g2.getTransform();
        try {
            //Move the origin to bottom-left, flip y axis
            g2.scale(1.0, -1.0);
            g2.translate(0, -h - insets.top);
    
            int xpoints[] = { 20, 30, 30, 35, 25, 15, 20 };
            int ypoints[] = { 10, 10, 30, 30, 45, 30, 30 };
            int npoints = 7;
            g2.fillPolygon(xpoints, ypoints, npoints);
        }
        finally {
          //restore
          g2.setTransform(oldAT);
        }
    }
    

    full source

    【讨论】:

    • 改变多边形坐标不是比改变整个画布更容易(而且更快)吗?
    • @WChargin 我确实解释过,在 Java 2D 中,左上角首先是 (0, 0)。我提出了一个答案,使平台遵循 OP 认为的数据的自然表示,但没有什么可以阻止发布相反的答案。
    猜你喜欢
    • 1970-01-01
    • 2011-01-03
    • 2018-09-10
    • 2010-12-20
    • 1970-01-01
    • 1970-01-01
    • 2017-07-17
    • 2016-05-05
    • 2020-04-14
    相关资源
    最近更新 更多