求任意多边形内一点

SkPoint findPointinPolygon(const std::vector& polygon)
{
	if (polygon.size() < 3)
		return SkPoint::Make(-1,-1);

	SkPoint p1,p2,p3;			//取多边形任意3个点
	p1 = polygon[0];p2 = polygon[1];p3 = polygon[2];

	//求角平分线
	Wm5::Vector2d v1,v2,v_mid;
	v1 = Wm5::Vector2d(p1.fX-p2.fX,p1.fY-p2.fY);
	v2 = Wm5::Vector2d(p3.fX-p2.fX,p3.fY-p2.fY);
	v_mid = v1/v1.Length()+v2/v2.Length();

	if (v_mid.Length() == 0)
		return SkPoint::Make(-1,-1);

	//构造角平分线直线
	CAglMat::AlgLine linMid;
	linMid.m_pt.X() = p2.fX;
	linMid.m_pt.Y() = p2.fY;
	v_mid.Normalize();
	linMid.m_direct.X() = v_mid.X();
	linMid.m_direct.Y() = v_mid.Y();

	//求角平分线与各分的交点
	CAglMat cam;
	vector	intrPoints;
	for (int i = 2 ; i < polygon.size() ; i++ )
	{
		Wm5::Vector2d v1Temp,v2Temp;
		v1Temp = Wm5::Vector2d(polygon[i].fX,polygon[i].fY);
		if (i==polygon.size()-1)
			v2Temp = Wm5::Vector2d(polygon[0].fX,polygon[0].fY);
		else
			v2Temp = Wm5::Vector2d(polygon[i+1].fX,polygon[i+1].fY);
		CAglMat::AlgLine segment;
		segment.m_pt.X() = v1Temp.X();
		segment.m_pt.Y() = v1Temp.Y();
		segment.m_direct.X() = (v2Temp-v1Temp).X();
		segment.m_direct.Y() = (v2Temp-v1Temp).Y();

		Wm5::Vector2f ptIntr;
		cam.LineIntersec(linMid,segment,ptIntr);
		if (cam.IsOnSegment(ptIntr,Wm5::Vector2f(v1Temp.X(),v1Temp.Y()),
			Wm5::Vector2f(v2Temp.X(),v2Temp.Y())))
		{
			intrPoints.push_back(SkPoint::Make(ptIntr.X(),
				ptIntr.Y()));
			
		}
	}

	if (intrPoints.size() == 0)
		return SkPoint::Make(-1,-1);

	//交点到p2的距离
	vector distOfp2;
	for (int i = 0 ; i < intrPoints.size() ; i++ )
	{
		Wm5::Vector2d v_temp = Wm5::Vector2d(p2.fX-intrPoints[i].fX,p2.fY-intrPoints[i].fY); 
		distOfp2.push_back(v_temp.Length());
	}

	//求出最短距离
	int minLengthIndex = 0;
	double minLength = *min_element(distOfp2.begin(),distOfp2.end());
	for ( int i = 0; i < distOfp2.size() ; i++ )
	{
		if (minLength == distOfp2[i])
		{
			minLengthIndex = i;
			break;
		}
	}

	//所求点即为p2和最后距离点的中点
	SkPoint resultPoint = intrPoints[minLengthIndex];
	Wm5::Vector2d resultVector2d = Wm5::Vector2d((resultPoint.fX+p2.fX)/2,
		(resultPoint.fY+p2.fY)/2);

	vector	v_poly;	
	for (int i = 0; i < polygon.size() ; i++ )
	{
		v_poly.push_back(Wm5::Vector2d(polygon[i].fX,polygon[i].fY));
	}
	Wm5::PointInPolygon2d ptInPoly(v_poly.size(),&v_poly[0]);

	if (ptInPoly.Contains(resultVector2d))
	{
		return resultPoint;
	}

	return SkPoint::Make(-1,-1);
}

你可能感兴趣的:(c++算法)