6

如何在 java 中向应用程序顶部绘制一个矩形?通常 drawRect 方法向底部绘制我尝试使用负数但这不起作用

Graphics g = p.getGraphics();
g.fillRect(50, 200,50,100);
4

3 回答 3

10

在矩形中,X 和 Y 坐标代表左上角。然后长度和宽度远离定义点。您的示例绘制了一个矩形,其左上角为 50,200,宽度为 50,高度为 100,两者都在正方向上远离这些点。如果您想要一个 50,200 代表左下角的矩形,只需从该 y 坐标 (200) 中减去高度,并将其用作起始 y:

Graphics g = p.getGraphics();
g.fillRect(50, 100, 50, 100);

要解决您的示例,请尝试以下操作(我将只使用矩形对象而不是实际填充图形):

int baseline = 200;
Rectangle rect1 = new Rectangle(50, baseline - 100, 50, 100);
Rectangle rect2 = new Rectangle(150, baseline - 50, 50, 50);
Rectangle rect3 = new Rectangle(250, baseline - 80, 50, 80);

在图形对象上用这些尺寸填充矩形后,您将拥有三个矩形,每个宽度为 50,间隔 50,底部都在 y=200 线上。

于 2012-09-19T22:48:02.480 回答
2

Java 的Graphics类假定原点(0, 0)是框架的左上角,(1, 1)(0, 0). 这与数学相反,其中标准笛卡尔平面的原点是左下角,并且(1, 1)在 的上方和右侧(0, 0)

此外,Java 不允许您对宽度和高度使用负值。这导致特殊的逻辑通常将矩形与正常的正尺寸矩形区别对待。

为了得到你想要的,首先扭转你对 JavaGraphics坐标系中 y 坐标的想法。正 y 下降,而不是上升(尽管正 x 仍然是正确的,就像标准笛卡尔图一样)。

话虽如此,drawRect和的字段fillRect是:

  1. 矩形左上角的 x 坐标
  2. 矩形左上角的 y 坐标
  3. 矩形的正宽度
  4. 矩形的正高度

佐伊的回答展示了如何获得你想要的东西的一个很好的例子,我只是想你可能想要更彻底地解释为什么“drawRect方法会趋于底部”。

于 2012-09-19T23:04:09.853 回答
1

运行它..在小程序窗口上向任何方向拖放鼠标..看看发生了什么......希望你能从中得到一些想法......

//Simulation of the desktop screen

package raj_java;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class DesktopDemo extends Applet implements MouseListener, MouseMotionListener {

    int x1, y1, x2, y2;
    Image img;

    public void init() {
        setSize(1200, 700);
        setVisible(true);
        img = getImage(getCodeBase(), "Nature.jpg");
        addMouseListener(this);
        addMouseMotionListener(this);
    }

    public void mouseEntered(MouseEvent me) {
        //blank
    }

    public void mouseExited(MouseEvent me) {
        //blank
    }

    public void mouseClicked(MouseEvent me) {
        //blank
    }

    public void mouseReleased(MouseEvent me) {
        Graphics g = getGraphics();
        g.drawImage(img, 0, 0, 1200, 700, this);
    }

    public void mouseMoved(MouseEvent me) {
        //blank
    }

    public void mousePressed(MouseEvent me) {
        x1 = me.getX();
        y1 = me.getY();
    }

    public void mouseDragged(MouseEvent me) {
        x2 = me.getX();
        y2 = me.getY();
        repaint();
    }

    public void paint(Graphics g) {
        g.drawImage(img, 0, 0, 1200, 700, this);
        g.setColor(new Color(10, 99, 126));
        g.drawLine(x1, y1, x2, y1);
        g.drawLine(x2, y1, x2, y2);
        g.drawLine(x2, y2, x1, y2);
        g.drawLine(x1, y2, x1, y1);
        g.setColor(new Color(193, 214, 220, 70));
        int width = Math.abs(x2 - x1);
        int height = Math.abs(y2 - y1);
        if(x2 < x1) {
            g.fillRect(x2, y1, width, height);
        }else if(y2 < y1) {
            g.fillRect(x1, y2, width, height);
        }else {
            g.fillRect(x1, y1, width, height);
        }
    }

}
于 2017-02-04T10:51:36.773 回答