Is there any easy way to draw a circle onto a JPanel?

做~自己de王妃 提交于 2019-12-20 05:23:29

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!