计算两条直线QLineF的重叠部分
效果
使用示例
QLineF intersection;
bool isSuccess = getOverlapSegment(line1, line2, intersection);
源码
bool getOverlapSegment(const QLineF& line1, const QLineF& line2, QLineF& overlap)
{
qreal slope1 = (line1.p2().y() - line1.p1().y()) / (line1.p2().x() - line1.p1().x());
qreal slope2 = (line2.p2().y() - line2.p1().y()) / (line2.p2().x() - line2.p1().x());
if (qAbs(slope1 - slope2) < 0.0001) {
if (qAbs(line1.p1().x() - line2.p2().x()) > 0.0001 && qAbs(line1.p1().y() - line2.p2().y()) > 0.0001 &&
qAbs(line1.p2().x() - line2.p1().x()) > 0.0001 && qAbs(line1.p2().y() - line2.p1().y()) > 0.0001) {
return false;
}
}
qreal x = (slope1 * line1.p1().x() - slope2 * line2.p1().x() + line2.p1().y() - line1.p1().y()) / (slope1 - slope2);
qreal y = slope1 * (x - line1.p1().x()) + line1.p1().y();
if (x < qMin(line1.p1().x(), line1.p2().x()) || x > qMax(line1.p1().x(), line1.p2().x()) ||
x < qMin(line2.p1().x(), line2.p2().x()) || x > qMax(line2.p1().x(), line2.p2().x()) ||
y < qMin(line1.p1().y(), line1.p2().y()) || y > qMax(line1.p1().y(), line1.p2().y()) ||
y < qMin(line2.p1().y(), line2.p2().y()) || y > qMax(line2.p1().y(), line2.p2().y())) {
return false;
}
qreal start1 = qMin(line1.p1().x(), line1.p2().x());
qreal end1 = qMax(line1.p1().x(), line1.p2().x());
qreal start2 = qMin(line2.p1().x(), line2.p2().x());
qreal end2 = qMax(line2.p1().x(), line2.p2().x());
qreal overlapStart = qMax(start1, start2);
qreal overlapEnd = qMin(end1, end2);
if (overlapStart <= overlapEnd) {
qreal minY1 = qMin(line1.p1().y(), line1.p2().y());
qreal maxY1 = qMax(line1.p1().y(), line1.p2().y());
qreal minY2 = qMin(line2.p1().y(), line2.p2().y());
qreal maxY2 = qMax(line2.p1().y(), line2.p2().y());
qreal overlapMinY = qMax(minY1, minY2);
qreal overlapMaxY = qMin(maxY1, maxY2);
overlap.setP1(QPointF(overlapStart, overlapMinY));
overlap.setP2(QPointF(overlapEnd, overlapMaxY));
return true;
}
return false;
}