绘制矩形和网格

时间:2013-01-08 00:52:01

标签: java applet graphics2d drawrectangle

如果有人能帮助我,我将非常感激。

我的课程有2节课。一个绘制一个矩形和一个网格,另一个是查看器。 问题是,当我尝试更改greed +矩形的位置,即更新Viewer类中的X和Y常量时,比例会发生变化。仅当X = 0且Y = 0时,网格才适合。

我使用相同的坐标数组来绘制网格和矩形,但不知何故比例是错误的,这让我感到惊讶。

谢谢。

我的代码:

import java.applet.Applet;
import java.awt.Graphics;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.math.BigDecimal;


public class Viewer extends Applet {
  public static final double R_WDTH = 12;//rectangle width
  public static final double X = 10;//the grid fits in only when X=Y=0
  public static final double Y = 10;
  public static final int ROWS = 25;
  public static final int COLUMNS = 12;

  RectangleAndGrid cup = new RectangleAndGrid(X, Y, R_WDTH, ROWS, COLUMNS);

  public void paint(Graphics g) {
    cup.draw((Graphics2D)g);
  }
}


public class RectangleAndGrid {
  private double x, y, blockWidth;
  private int rows, columns;
  private double coordX[][], coordY[][];
  private Rectangle2D.Double cupSpace;

  public RectangleAndGrid(double cX, double cY, double givenBlockWidth, int r, int c){
    x = cX;
    y = cY;
    blockWidth = givenBlockWidth;
    rows = r;
    columns = c;

    BigDecimal currX = BigDecimal.valueOf(x);
    BigDecimal currY = BigDecimal.valueOf(y);
    coordX = new double[rows + 1][columns + 1];
    coordY = new double[rows + 1][columns + 1];
    for(int i = 0; i <= rows; i++){
      for(int j = 0; j <= columns; j++){
        coordX[i][j] = currX.doubleValue();
        coordY[i][j] = currY.doubleValue();
        currX = currX.add(BigDecimal.valueOf(blockWidth));
      }
      currX = BigDecimal.valueOf(x);
      currY = currY.add(BigDecimal.valueOf(blockWidth));
    }

    cupSpace = new Rectangle2D.Double(coordX[0][0], coordY[0][0], coordX[rows][columns], coordY[rows][columns]);
  }

  public void draw(Graphics2D g2d){
    g2d.setColor(Color.CYAN);
    g2d.fill(cupSpace);
    g2d.setColor(Color.BLACK);
    g2d.draw(cupSpace);

    Line2D.Double line = new Line2D.Double();
    for(int i = 0; i <= rows; i++){
      line.setLine(coordX[i][0], coordY[i][0], coordX[i][columns], coordY[i][columns]);
      g2d.draw(line);
    }
    for(int i = 0; i <= columns; i++){
      line.setLine(coordX[0][i], coordY[0][i], coordX[rows][i], coordY[rows][i]);
      g2d.draw(line);
    }
  }
}

1 个答案:

答案 0 :(得分:3)

首先,你的方法是“小”怪,不完全坏,只是有点奇怪 - 恕我直言

Rectangle2D有四个参数,xywidthheight。在您的代码中,您正在通过网格的顶部,左侧和右下角,这意味着,“杯子”的宽度/高度实际上更宽x像素(并且y像素更高)

基本上,您需要从右下角坐标中减去x / y偏移量...

cupSpace = new Rectangle2D.Double(coordX[0][0], coordY[0][0], coordX[rows][columns] - coordX[0][0], coordY[rows][columns] - coordY[0][0]);