一、原理简述
如上图所示,当有一条线段 a ,b (长度大于0.5)时,要减去0.5的长度,得到线段c,b。
算法思路:相似三角形原理
//这里方便我直接使用了CGAL几何计算库 当然你也可以自己自定义数据结构
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Segment_2.h>
#include <CGAL/Vector_2.h>
#include <iostream>
typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef K::Point_2 Point_2; //二维点坐标
typedef CGAL::Segment_2<K> Segment_2; //二维线段
Segment_2 reduce_segment(const Segment_2& seg,float value)
{
if (seg.squared_length() < value*value)
{
std::cout << "减少长度过大,超过线段长度......" << std::endl;
exit(-1);
}
float x1, y1;
if (seg.target().y() == seg.source().y())
{
x1 = seg.source().x() + value;
y1 = seg.source().y();
return Segment_2(Point_2(x1, y1), seg.target());
}
if (seg.source().x() == seg.target().x())
{
x1 = seg.source().x();
y1 = seg.source().y() + value;
return Segment_2(Point_2(x1, y1), seg.target());
}
x1 = (value * (seg.target().x() - seg.source().x())) / std::sqrt(seg.squared_length());
y1 = (value * (seg.target().y() - seg.source().y())) / std::sqrt(seg.squared_length());
return Segment_2(Point_2(x1, y1), seg.target());
}
int main()
{
Segment_2 seg(Point_2(0,0), Point_2(6,8));
Segment_2 get_seg = reduce_segment(seg, 5);
std::cout << "source ---> x : " << get_seg.source().x() << " y:" << get_seg.source().y() << std::endl;
std::cout << "end ---> x : " << get_seg.target().x() << " y:" << get_seg.target().y() << std::endl;
return 0;
}
//通过这个首尾方向计算思路,你也可以计算出其他首尾方向的计算方法
<如有误,请指出,谢谢>