这里,蓝线是要修剪的多边形边。黄色,线是剪切多边形的边缘。
//Sutherland-Holdgman Line Clipping
#include "Line2d.h"
#include "Rectangle2d.h"
#include "Coordinates2d.h"
#include "Bits.h"
#include "Polygon2d.h"
#include <list>
typedef enum PointPosition
{
Left, Right
} PointPosition;
typedef enum LinePosition
{
CompletelyOut, CompletelyIn, ClippingCandidate, ClippingCandidateExtended
} LinePosition;
void EnumToString(LinePosition lnPos)
{
switch(lnPos)
{
case CompletelyOut:
std::cout<<lnPos<<". CompletelyOut";
break;
case CompletelyIn:
std::cout<<lnPos<<". CompletelyIn";
break;
case ClippingCandidate:
std::cout<<lnPos<<". ClippingCandidate";
break;
case ClippingCandidateExtended:
std::cout<<lnPos<<". ClippingCandidateExtended";
break;
}
}
class ClippingPolygon2d
{
private:
Rectangle2d rectangle;
Polygon2d polygon;
PointPosition CheckPointAgainstALine(Line2d line, Point2d pt)
{
double c = (((line.GetEnd().x - line.GetStart().x)
*(pt.y - line.GetStart().y))
-((line.GetEnd().y - line.GetStart().y)
*(pt.x - line.GetStart().x)));
if(c>=0) return Left;
else return Right;
}
public:
LinePosition CheckLineAgainstEdge(Line2d polygonEdge, Line2d line)
{
LinePosition linePosition;
PointPosition startPoint = CheckPointAgainstALine(polygonEdge, line.GetStart());
PointPosition endPoint = CheckPointAgainstALine(polygonEdge, line.GetEnd());
if(startPoint==Left && endPoint==Left)
{
linePosition = CompletelyOut;
}
else if(startPoint==Right && endPoint==Right)
{
linePosition = CompletelyIn;
}
else if(startPoint==Left && endPoint==Right)
{
linePosition = ClippingCandidateExtended;
}
else if(startPoint==Right && endPoint==Left)
{
linePosition = ClippingCandidate;
}
return linePosition;
}
};
int main()
{
Coordinates2d::ShowWindow("Sutherland-Hodgeman Line Clipping");
ClippingPolygon2d clip;
Line2d edge(Point2d(20,20), Point2d(160,140));
Line2d ln(Point2d(100,120), Point2d(100,140));
LinePosition lnPos = clip.CheckLineAgainstEdge(edge, ln);
EnumToString(lnPos);
Coordinates2d::Draw(edge, Blue);
Coordinates2d::Draw(ln, Yellow);
Coordinates2d::Wait();
return 0;
}
<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9UVjhXSi5wbmcifQ==” alt =“在此处输入图像说明”>
您可以使用std::vector
而不初始化其大小,并且它支持随机访问。要添加为空的std::vector
,请使用push_back
std::vector<MyType> vec;
vec.push_back(MyType(10, 'a', "Hi"));
vec.push_back(MyType(20, 'b', "Hello"));
vec.push_back(MyType(30, 'c', "Bye"));
MyType t = vec[1];//20,'b', "Hello"...
Edit:此答案是最初提出的问题。