[英]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),而拖动应是椭圆的半径。
Graphics#drawRect
and Graphics#drawOval
expect the parameters to mean x, y, width, height
, not x1, y1, x2, y2
... Graphics#drawRect
和Graphics#drawOval
期望参数表示x, y, width, height
,而不是x1, y1, x2, y2
... 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: 让我为简洁改变从变量名
startPoint
到sp
,并从controlPoint
到cp
,那么这些改变你的代码应该做的伎俩:
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.