如何向函数java添加转换

时间:2020-05-11 17:50:58

标签: java graphics

我编写了一个绘制三角形的函数,并且可以使用,但是我想使用诸如缩放和反射之类的函数添加一些转换方法?

代码如下:

public void drawTriangle(Graphics g, int x5, int y5, int x6, int y6) {
Graphics2D g2 = (Graphics2D)g;
Point2D center = new Point2D.Double(x5,y5);
Point2D point1 = new Point2D.Double(x6,y6);
double x1 = point1.getX() - center.getX();
double y1 = point1.getY() - center.getY();
double x2 = x1 * Math.cos((Math.PI / 180) *120) - y1 * Math.sin((Math.PI / 180) *120);
double y2 = x1 * Math.sin((Math.PI / 180) *120) + y1 * Math.cos((Math.PI / 180) *120);
double xx = x2 + center.getX();
double yy = y2 + center.getY();
double i1 = point1.getX() - center.getX();
double w1 = point1.getY() - center.getY();
double i2 = i1 * Math.cos((Math.PI / 180) *240) - w1 * Math.sin((Math.PI / 180) *240);
double w2 = i1 * Math.sin((Math.PI / 180) *240) + w1 * Math.cos((Math.PI / 180) *240);
double xxx = i2 + center.getX();
double yyy = w2 + center.getY();
Point2D point2 = new Point2D.Double(xx,yy);
Point2D point3 = new Point2D.Double(xxx,yyy);
g2.draw(new Line2D.Double(point1, point2));
g2.draw(new Line2D.Double(point2, point3));
g2.draw(new Line2D.Double(point3, point1));
}

1 个答案:

答案 0 :(得分:0)

您使用.setTransform.getTransform.scale方法,请参见下面的代码中的注释//a0//a1//a2。我没有测试:

public void drawTriangle(Graphics g, int x5, int y5, int x6, int y6) {
Graphics2D g2 = (Graphics2D)g;
Point2D center = new Point2D.Double(x5,y5);
Point2D point1 = new Point2D.Double(x6,y6);
double x1 = point1.getX() - center.getX();
double y1 = point1.getY() - center.getY();
double x2 = x1 * Math.cos((Math.PI / 180) *120) - y1 * Math.sin((Math.PI / 180) *120);
double y2 = x1 * Math.sin((Math.PI / 180) *120) + y1 * Math.cos((Math.PI / 180) *120);
double xx = x2 + center.getX();
double yy = y2 + center.getY();
double i1 = point1.getX() - center.getX();
double w1 = point1.getY() - center.getY();
double i2 = i1 * Math.cos((Math.PI / 180) *240) - w1 * Math.sin((Math.PI / 180) *240);
double w2 = i1 * Math.sin((Math.PI / 180) *240) + w1 * Math.cos((Math.PI / 180) *240);
double xxx = i2 + center.getX();
double yyy = w2 + center.getY();
Point2D point2 = new Point2D.Double(xx,yy);
Point2D point3 = new Point2D.Double(xxx,yyy);

// a0: Save current transform
AffineTransform saveAT = g2.getTransform();

// a1: Your transformation
g2.scale(2.0, -1.0); // Scale x coordinates by 2 and reflect y coordinates

g2.draw(new Line2D.Double(point1, point2));
g2.draw(new Line2D.Double(point2, point3));
g2.draw(new Line2D.Double(point3, point1));

// a2: Restore previous transform
g2.setTransform(saveAT);

}

在此处查看Graphics2D API:https://docs.oracle.com/javase/7/docs/api/java/awt/Graphics2D.html

相关问题