使用System.Drawing.Region 类 先用那些点构造出Region 对象 Intptr hregion = region.GetHrgn( Graphics g ); 获得region句柄 调用 BOOL PtInRegion( HRGN hrgn, // handle to region int X, // x-coordinate of point int Y // y-coordinate of point );判断是否在多边形里
public bool PtInPath(Point pt, Point[] points) { GraphicsPath path = new GraphicsPath(); path.StartFigure(); for (int i = 0; i < points.Length / 2; i++) { path.AddLine(points[i * 2], points[i * 2 + 1]);
用创建多边形的每一条线构成一个GraphicsPath,然后调用GraphicsPath.IsVisible能够判断一个点是否在一个封闭的区间内。
先用那些点构造出Region 对象
Intptr hregion = region.GetHrgn( Graphics g );
获得region句柄
调用
BOOL PtInRegion(
HRGN hrgn, // handle to region
int X, // x-coordinate of point
int Y // y-coordinate of point
);判断是否在多边形里
{
GraphicsPath path = new GraphicsPath();
path.StartFigure();
for (int i = 0; i < points.Length / 2; i++)
{
path.AddLine(points[i * 2], points[i * 2 + 1]);
}
if (points.Length % 2 != 0)
{
path.AddLine(points[points.Length - 1], points[points.Length - 1]);
}
path.CloseFigure();
this.CreateGraphics().DrawPath(new Pen(Color.FromArgb(255, 255, 0, 0), 2), path);
return path.IsVisible(pt);
}
//调用
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
bool re=PtInPath(new Point(e.X, e.Y), new Point[] { new Point(0, 0), new Point(300, 0), new Point(300, 100),new Point(200,150),new Point(150,125),new Point(139,110), new Point(0, 100) });
MessageBox.Show(re.ToString());
}