我遇到了一些麻烦,无法找到经典的“Contains”方法,该方法返回一个点是否在矩形、椭圆或其他对象内。这些对象在画布上。
我已经尝试使用VisualTreeHelper.FindElementsInHostCoordinates,但我找不到方法。
我该如何做?
这对我很有效。*(如果您觉得有用,请投票!)
public bool Contains(Ellipse Ellipse, Point location)
{
Point center = new Point(
Canvas.GetLeft(Ellipse) + (Ellipse.Width / 2),
Canvas.GetTop(Ellipse) + (Ellipse.Height / 2));
double _xRadius = Ellipse.Width / 2;
double _yRadius = Ellipse.Height / 2;
if (_xRadius <= 0.0 || _yRadius <= 0.0)
return false;
/* This is a more general form of the circle equation
*
* X^2/a^2 + Y^2/b^2 <= 1
*/
Point normalized = new Point(location.X - center.X,
location.Y - center.Y);
return ((double)(normalized.X * normalized.X)
/ (_xRadius * _xRadius)) + ((double)(normalized.Y * normalized.Y) / (_yRadius * _yRadius))
<= 1.0;
}
使用C#并不是那么简单。
首先,您需要一个GraphicsPath
。然后使用想要的形状初始化它,对于椭圆形,使用AddEllipse
方法。接着使用IsVisible
方法检查您的点是否包含在该形状内。您可以使用各种AddLine
方法测试任意形状。
例如:
Rectangle myEllipse = new Rectangle(20, 20, 100, 50);
// use the bounding box of your ellipse instead
GraphicsPath myPath = new GraphicsPath();
myPath.AddEllipse(myEllipse);
bool pointWithinEllipse = myPath.IsVisible(40,30);
GraphicsPath
,有很多在线教程,例如http://www.c-sharpcorner.com/uploadfile/mahesh/graphics-path-in-silverlight/。 - Dunes