问题
I'm having trouble using the drawOval(x,y,width,height) method, which assumes that the x and y values represent the coordinates of the "upper left corner of the oval to be drawn" (javadoc)
I want the x and y values to represent the center-point of a circle. How do I do this? Thanks
回答1:
A simple solution, if you have the width/height declared in advance, would be to use the drawOval method as follows:
drawOval( x - (width/2), y - (height/2), width, height);
This will ensure that (x, y) is at the center of the oval.
Why?
Let's say (x, y) is (10, 10) and you want to draw an oval of (height, width) = (10, 10).
drawOval(x, y, height width);
would then draw the top-right of the oval at (10, 10), and the bottom-left would be at (10 + 10, 10 + 10) = (20, 20).
On the other hand, if you use
drawOval( x - (width/2), y - (height/2), height, width);
the top-right of the oval would be drawn at ( 10 - (10/2), 10 - (10/2) ) = (5, 5) and the bottom would be drawn at (5 + 10, 5 + 10) = (15, 15). The center would then be (10, 10) :)
来源:https://stackoverflow.com/questions/10219349/is-there-any-easy-way-to-draw-a-circle-onto-a-jpanel