简体   繁体   English

在方形usnig java挥杆内绘制钻石

[英]drawing a diamond inside a square usnig java swing

I am having some trouble while using swing to draw a diamond inside a square. 使用秋千在正方形内绘制菱形时遇到麻烦。 My code is this,please some one have a look at it and let me know if you can provide a fullfunctional code which is working in creating a diamond inside a square. 我的代码是这个,请有人看一下,让我知道您是否可以提供在正方形内创建菱形的全功能代码。 The code is:- 代码是:-

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);
}
}

To keep the the diamond inside the sqaure, simply 1. Draw a rectangle 2. Rotate the rectangle about its center. 要将钻石保留在方形内,只需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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM