任意直线分割多边形,返回分割后的多边形
效果
使用示例
QPolygonF LineSegmentationPolygon ( const QPolygonF& poly, const QLineF& line, SideToRemove sideToRemove)
源码
enum class SideToRemove {
None,
Left,
Right
} ;
QPolygonF LineSegmentationPolygon ( const QPolygonF& poly, const QLineF& line, SideToRemove sideToRemove)
{
auto AppendPointIfDifferent = [ ] ( QPolygonF& polygon, const QPointF& point) {
if ( polygon. isEmpty ( ) || polygon. last ( ) != point) {
polygon << point;
}
} ;
QPolygonF resultPoly;
for ( int i = 0 ; i < poly. size ( ) ; ++ i) {
QPointF p1 = poly[ i] ;
QPointF p2 = poly[ ( i + 1 ) % poly. size ( ) ] ;
qreal d1 = line. dx ( ) * ( p1. y ( ) - line. y1 ( ) ) - line. dy ( ) * ( p1. x ( ) - line. x1 ( ) ) ;
qreal d2 = line. dx ( ) * ( p2. y ( ) - line. y1 ( ) ) - line. dy ( ) * ( p2. x ( ) - line. x1 ( ) ) ;
if ( ( sideToRemove == SideToRemove:: None) ||
( sideToRemove == SideToRemove:: Left && d1 >= 0 ) ||
( sideToRemove == SideToRemove:: Right && d1 <= 0 ) ) {
AppendPointIfDifferent ( resultPoly, p1) ;
}
if ( ( d1 * d2) < 0 ) {
qreal x = ( p1. x ( ) * d2 - p2. x ( ) * d1) / ( d2 - d1) ;
qreal y = ( p1. y ( ) * d2 - p2. y ( ) * d1) / ( d2 - d1) ;
AppendPointIfDifferent ( resultPoly, QPointF ( x, y) ) ;
}
QLineF edge ( p1, p2) ;
QPointF intersectPoint;
if ( line. intersect ( edge, & intersectPoint) == QLineF:: BoundedIntersection) {
AppendPointIfDifferent ( resultPoly, intersectPoint) ;
}
}
return resultPoly;
}