Java 怎么用坐标绘制点和标签

2019年8月19日22:41:09 评论 20

1.简介

Java 怎么用坐标绘制点和标签?——请看下文。

2.代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

import java.util.ArrayList;
import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.geom.*;

public class Main{
    public static final int scene_offset_x = 100;
    public static final int scene_offset_y = 500;
    public static final double point_diameter = 6.5;
    
    public static void drawPoints(Graphics2D g, ArrayList<Point> points,
            Color color, boolean labels) {
        FontMetrics fm = g.getFontMetrics();
        double point_radius = point_diameter / 2.0;
        g.setPaint(color);

        for (Point p : points) {
            Point2D.Double point = new Point2D.Double(p.getX(), p.getY());
            
            invertYAxisAffineTransform().transform(point, point);

            g.fill(new Ellipse2D.Double(point.getX() - point_radius, point
                    .getY() - point_radius, point_diameter, point_diameter));

            if (labels) {
                String text = p.toString();
                g.drawString(
                        text,
                        (float) (point.getX() - fm.stringWidth(text) / 2.0),
                        (float) (point.getY() - fm.getHeight()));
            }
        }
    }
    
    public static AffineTransform invertYAxisAffineTransform() {
        AffineTransform newAT = new AffineTransform();
        
        newAT.translate(scene_offset_x, scene_offset_y);
        
        newAT.scale(1.0, -1.0);
        return newAT;
    }
}

 

3.总结

示例代码演示了 Java 怎么用坐标绘制点和标签,具体步骤参见示例代码。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: