Java - 画一个三角形

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21564837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:23:48  来源:igfitidea点击:

Java - draw a triangle

javarandomgeometrydraw

提问by user3235376

Hey I know that it is simple to draw oval/rectangle and fill it using

嘿,我知道绘制椭圆/矩形并使用填充它很简单

g.fillOval(30, 40, 20, 20);

but how to draw a triangle? It would be the best if it would have random coordinates.

但是怎么画三角形呢?如果它有随机坐标,那将是最好的。

采纳答案by MadProgrammer

There are at least two basics ways you can achieve this, based on your needs.

根据您的需要,至少有两种基本方法可以实现这一点。

You could use Polygonor you could make use the 2D Graphics Shape API

你可以使用Polygon或者你可以使用2D Graphics Shape API

Which you might choose comes down to your requirements. Polygonrequires you to know, in advance the position of the points within 3D space, where the ShapeAPI gives you more freedom to define the shape without caring about the position in advance.

您可以选择哪个取决于您的要求。 Polygon需要您提前知道点在 3D 空间中的位置,ShapeAPI 使您可以更自由地定义形状,而无需事先关心位置。

This makes the ShapeAPI more flexible, in that you can define the shape once and simply translate the Graphicscontext as needed and repaint it.

这使得ShapeAPI 更加灵活,因为您可以一次定义形状,然后Graphics根据需要简单地转换上下文并重新绘制它。

For example...

例如...

Triangle

三角形

Red is a Polygon, green is a Shape, which is translated into position...

红色是 a Polygon,绿色是 a Shape,翻译成位置...

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.geom.Path2D;
import java.awt.geom.Point2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TriangleTest {

    public static void main(String[] args) {
        new TriangleTest();
    }

    public TriangleTest() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private TriangleShape triangleShape;
        private Polygon poly;

        public TestPane() {
            triangleShape = new TriangleShape(
                    new Point2D.Double(50, 0),
                    new Point2D.Double(100, 100),
                    new Point2D.Double(0, 100)
            );

            poly = new Polygon(
                    new int[]{50, 100, 0},
                    new int[]{0, 100, 100},
                    3);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setColor(Color.RED);
            g2d.fill(poly);

            g2d.setColor(Color.GREEN);
            g2d.translate(50, 100);
            g2d.fill(triangleShape);
            g2d.dispose();
        }
    }

    public class TriangleShape extends Path2D.Double {

        public TriangleShape(Point2D... points) {
            moveTo(points[0].getX(), points[0].getY());
            lineTo(points[1].getX(), points[1].getY());
            lineTo(points[2].getX(), points[2].getY());
            closePath();
        }

    }

}

回答by Martijn Courteaux

Using the legacy Graphicsclass, this would be done by using the legacy method
drawPolygon(int[] x, int[] y, int pointCount).

使用遗留Graphics类,这将通过使用遗留方法来完成
drawPolygon(int[] x, int[] y, int pointCount)

The newer class Graphics2Dsupports a much nicer implementation using Path2Ds. You will need either the draw(Shape)or fill(Shape)method. Given the fact that almost everywhere in Java a Graphicsobject is actually a Graphics2Dobject, you can cast it so, that is the way to go, IMHO.

较新的类Graphics2D使用Path2Ds支持更好的实现。您将需要draw(Shape)orfill(Shape)方法。鉴于 Java 中几乎所有地方的Graphics对象实际上都是一个Graphics2D对象,您可以将其强制转换,这就是要走的路,恕我直言。

Graphics g = ...;
Graphics2D g2d = (Graphics2D) g;
Path2D.Double triangle = new Path2D.Double();
triangle.moveTo(x1, y1);
triangle.pathTo(x2, y2);
triangle.pathTo(x3, y3);
triangle.closePath();
g2d.fill(triangle);