先定义个点、线结构
typedef struct tagStruVertex
{
double x;
double y;
double distanceTo(const tagStruVertex& point) const
{
return sqrt((x - point.x) * (x - point.x) + (y - point.y) * (y - point.y));
}
bool equal(const tagStruVertex& point) const
{
if (point.x == x && point.y == y)
{
return true;
}
return false;
}
}StruVertex;
typedef struct tagStruSegment
{
StruVertex start;
StruVertex end;
}StruSegment;
计算叉乘
double mult(StruVertex a, StruVertex b, StruVertex c)
{
return (a.x - c.x) * (b.y - c.y) - (b.x - c.x) * (a.y - c.y);
}
判断两线是否相交
//start1, end1为一条线段两端点 start2, end2为另一条线段的两端点 相交返回true, 不相交返回false
bool intersect(StruVertex start1, StruVertex end1, StruVertex start2, StruVertex end2)
{
if (max(start1.x, end1.x) < min(start2.x, end2.x))
{
return false;
}
if (max(start1.y, end1.y) < min(start2.y, end2.y))
{
return false;
}
if (max(start2.x, end2.x) < min(start1.x, end1.x))
{
return false;
}
if (max(start2.y, end2.y) < min(start1.y, end1.y))
{
return false;
}
//ac*ab < 0 或者 ab*ad<0
if (mult(start2, end1, start1) * mult(end1, end2, start1) < 0)
{
return false;
}
//ca*cd<0 或者 cd*cb<0
if (mult(start1, end2, start2) * mult(end2, end1, start2) < 0)
{
return false;
}
return true;
}
获取交点
StruVertex getLineNode(StruVertex start1, StruVertex end1, StruVertex start2, StruVertex end2)
{
StruVertex ret = start1;
double t = ((start1.x - start2.x) * (start2.y - end2.y) - (start1.y - start2.y) * (start2.x - end2.x)) / ((start1.x - end1.x) * (start2.y - end2.y) - (start1.y - end1.y) * (start2.x - end2.x));
ret.x += (end1.x - start1.x) * t;
ret.y += (end1.y - start1.y) * t;
return ret;
}
判断点是否在线上
bool onSegment(StruVertex pi, StruVertex pj, StruVertex Q)
{
if ((Q.x - pi.x) * (pj.y - pi.y) == (pj.x - pi.x) * (Q.y - pi.y) && min(pi.x, pj.x) <= Q.x && Q.x <= max(pi.x, pj.x) && min(pi.y, pj.y) <= Q.y && Q.y <= max(pi.y, pj.y)) {
return true;
}
else {
return false;
}
}

被折叠的 条评论
为什么被折叠?



