1

我在使用摆动在正方形内绘制钻石时遇到了一些麻烦。我的代码是这样的,请有人看一下,让我知道您是否可以提供一个全功能代码,用于在正方形内创建钻石。代码是: -

import javax.swing.*;
import java.awt.*;

public class MyDrawing extends JPanel
{
  static int width=250;
  static int height=250;
  static int x=0;
  static int y=0;
  private void doDrawing(Graphics g) 
  {

        Graphics2D g2d = (Graphics2D) g;

        g2d.setColor(Color.blue);

        //for (int i = 0; i <= 1000; i++) 
        g2d.drawRect(x, y, width,height);
        g2d.rotate(Math.toRadians(-45));
        System.out.println(Math.toRadians(-45));
        x=0;
        y=height/2;
        System.out.println(y);
        width=(int)Math.pow(Math.pow((width/2),2)*2,0.5);

        height=width;
        System.out.println("width:"+width+"height:"+height);
        g2d.drawRect(y, x, width,height);

}

@Override
public void paintComponent(Graphics g) {

    super.paintComponent(g);
    doDrawing(g);
}
}
4

1 回答 1

0

要将菱形保持在正方形内,只需 1. 绘制一个矩形 2. 围绕其中心旋转矩形。

Rectangle2D rectangle = new Rectangle2D.Double(20, 20, 50, 50);
g2.draw(rectangle);
AffineTransform transform = new AffineTransform();
transform.rotate(Math.PI/4, rectangle.getX() + rectangle.width/2,    rectangle.getY() + rectangle.height/2);
g2.draw(transform);
于 2013-10-07T07:26:16.707 回答