简体   繁体   English

如何使用鼠标拖动绘制矩形和椭圆形?

[英]How do you draw a rectangle and an oval using mouse dragging?

I understand how to use MouseMotionListener but I can't get the parameters right for drawing a rectangle and an oval. 我了解如何使用MouseMotionListener,但无法正确绘制矩形和椭圆形的参数。

This is my attempt at a rectangle, but the problem is if go to the left from the start point, the rectangle gets filled. 这是我尝试的矩形,但是问题是,如果从起点到左侧,则矩形会被填充。

public void draw(Graphics g) {

    g.drawRect((int)startPoint.getX(), (int)startPoint.getY(),(int)controlPoint.getX() - (int)startPoint.getX(),    (int) controlPoint.getY() - (int)startPoint.getY());

}

This is my method for a circle, this seems to work fine. 这是我转了一圈的方法,似乎工作正常。 But i cannot alter it for it to form an oval. 但是我不能改变它使其形成一个椭圆形。

public void draw(Graphics g) {
    g.drawOval((int)startPoint.getX() - (int)controlPoint.distance(startPoint),((int)startPoint.getY() - (int)controlPoint.distance(startPoint)),
            (int)controlPoint.distance(startPoint)*2,(int)controlPoint.distance(startPoint)*2);
}

The mousePressed must be the center(startPoint) and the drag should be the radius for an oval. mousePressed必须是中心(startPoint),而拖动应是椭圆的半径。

  • Both Graphics#drawRect and Graphics#drawOval expect the parameters to mean x, y, width, height , not x1, y1, x2, y2 ... Graphics#drawRectGraphics#drawOval期望参数表示x, y, width, height ,而不是x1, y1, x2, y2 ...
  • Your start points may be greater than your end points, resulting in either or both the width and/or height been negative values (based on width = x1 - x2 ). 您的起点可能大于终点,导致宽度和/或高度之一或两者均为负值(基于width = x1 - x2 )。 The Graphics API doesn't like negative values very much. Graphics API不太喜欢负值。 You will need to take this into consideration when calculating the starting points and size. 在计算起点和尺寸时,需要考虑到这一点。

The crust of the problem can be solved using something like... 问题的结局可以通过以下方式解决:

int minX = Math.min(currentX, startX);
int minY = Math.min(currentY, startY);
int maxX = Math.max(currentX, startX);
int maxY = Math.max(currentY, startY);

int x = minX;
int y = minY;
int width = maxX - minX;
int height = maxX - minX;

Take a look at java draws rectangle one way not both for a working example... 看一下Java绘制矩形的一种方法,不是一个可行的例子。

Let me for brevity change the variable names from startPoint to sp and from controlPoint to cp , then these changes to your code should do the trick: 让我为简洁改变从变量名startPointsp ,并从controlPointcp ,那么这些改变你的代码应该做的伎俩:

int minX = Math.min(sp.x, sp.y);
int minY = Math.min(sp.x, sp.y);
int width = Math.abs(cp.x - sp.x);
int height = Math.abs(cp.y - sp.y);

g.drawRect(minX, minY, width, height);
g.drawOval(minX, minY, width, height);

The reason is that those methods should receive the top-left corner coordinates, as well as the width and height of the bounding box of the rect/oval being drawn. 原因是这些方法应该接收左上角的坐标,以及所绘制的矩形/椭圆形的边界框的宽度和高度。

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

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