How can I tell if the mouse pointer is inside a path defined by Bezier curves and lines?

╄→гoц情女王★ 提交于 2019-12-10 16:44:14

问题


I have a closed path consisting of multiple Bezier curves and straight line segments. How can I tell whether the current position of my mouse pointer is inside or outside the path?

Example of mouse leaving the area:

Example of mouse entering the area:


回答1:


First you should check if the graphics library you're using already provides this hit-testing.

If you have to code it yourself, then a completely precise answer would require solving quadratic or cubic equations (depending on the degree of your Bezier curves) to determine the intersection with these paths. There seems to be a paper on exactly this problem.

However I think it would be much more sensible to build a linear approximation to your path (i.e. evaluate the path densely) and then use a standard point-in-polygon test. This can be accurate to whatever tolerance you choose (e.g. one pixel).




回答2:


If the regions are relatively small, you could run a floodfill starting from the mouse location. If the floodfill goes outside of a bounding box (which you can precompute) then it's outside of the region.

See: http://en.wikipedia.org/wiki/Flood_fill




回答3:


To test whether a point is inside or outside a bezier path, draw a line in any direction from the point, and count the number of times the line crosses the path. If the number is odd, then you are inside, if it is even then you are outside.

So, an inside-ness test can be re-expressed as an intersection test. Intersections can be tackled in several ways. A relatively simple approach is to approximate your bezier patches with straight line segments using deCasteljau's algorithm, reducing the bezier-line intersection test to a series of line-line intersection tests.

Note that you can take several shortcuts in your calculation. If, for example, the line you're drawing lies completely outside the bounding box of a given bezier patch's control points, then you can assume that it's not going to cross the patch. You can take advantage of this particular shortcut when recursively splitting your curves with deCasteljau to discard split sections of curves that are not going to intersect your line segment.



来源:https://stackoverflow.com/questions/6444602/how-can-i-tell-if-the-mouse-pointer-is-inside-a-path-defined-by-bezier-curves-an

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