爪哇 - (在90度角符合刻度)绘制一个统治者 [英] Java - Draw a ruler (line with tick marks at 90 degree angle)

查看:157
本文介绍了爪哇 - (在90度角符合刻度)绘制一个统治者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Java AWT绘制面板线(的Line2D Graphics2D.drawLine())我想知道我怎么能画一条线与刻度线,类似于:

I'm using Java AWT to draw lines on a panel (Line2D and Graphics2D.drawLine()) and I'm wondering how I can draw a line with tick marks, similar to:

| ---- | ---- | ---- | ---- | ---- |

|----|----|----|----|----|

我知道的位置,我想在提前绘制蜱。

I know the positions I'd like to draw the ticks at in advance.

的线条可以是在任何位置,因此,蜱必须以一个角度相关联系到线路本身绘制。

The lines could be in any position, so the ticks must be drawn at an angle releative to the line itself.

我的基本几何形状和放大器;在Java中运用能力是失败了我。 :)

My basic geometry & ability to apply it in Java is failing me. :)

推荐答案

我建议你


  1. 实施尺子绘图法,从左至右绘制一个简单的水平标尺

  2. 使用的 Math.atan2

  3. 敷上 的AffineTransform 与调用尺子拉法之前的平移和旋转。

下面是一个完整的测试程序。 (在 Graphics.create 使用方法来创建原始图形对象的副本,所以我们不要弄乱原有转换。)

Here is a complete test-program. (The Graphics.create method is used to create a copy of the original graphics object, so we don't mess up the original transform.)

import java.awt.*;

public class RulerExample {

    public static void main(String args[]) {
        JFrame f = new JFrame();
        f.add(new JComponent() {

            private final double TICK_DIST = 20;

            void drawRuler(Graphics g1, int x1, int y1, int x2, int y2) {
                Graphics2D g = (Graphics2D) g1.create();

                double dx = x2 - x1, dy = y2 - y1;
                double len = Math.sqrt(dx*dx + dy*dy);
                AffineTransform at = AffineTransform.getTranslateInstance(x1, y1);
                at.concatenate(AffineTransform.getRotateInstance(Math.atan2(dy, dx)));
                g.transform(at);

                // Draw horizontal ruler starting in (0, 0)
                g.drawLine(0, 0, (int) len, 0);
                for (double i = 0; i < len; i += TICK_DIST)
                    g.drawLine((int) i, -3, (int) i, 3);
            }

            public void paintComponent(Graphics g) {
                drawRuler(g, 10, 30, 300, 150);
                drawRuler(g, 300, 150, 100, 100);
                drawRuler(g, 100, 100, 120, 350);
                drawRuler(g, 50, 350, 350, 50);
            }
        });

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

请注意,你可以很容易地画出蜱上面的数字。束带通话会经历同样的转型并获得很好的倾斜沿线。

Note, that you could just as easily draw numbers above the ticks. The drawString-calls would go through the same transformation and get nicely "tilted" along the line.

这篇关于爪哇 - (在90度角符合刻度)绘制一个统治者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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