计算两条直线QLineF的重叠部分
效果
使用示例
cpp
QLineF intersection;
bool isSuccess = GetOverlapSegment(line1, line2, intersection);
源码
cpp
// 判断两个QLineF对象在斜率相同时是否存在重叠部分
bool DoLineOverlapWithSameSlope(const QLineF& line1, const QLineF& line2)
{
qreal slope1 = line1.dy() / line1.dx();
qreal slope2 = line2.dy() / line2.dx();
// 引入误差范围
qreal epsilon = 1e-6;
if (std::abs(slope1 - slope2) > epsilon) {
return false; // 斜率不相等,直接返回false
}
qreal b1 = line1.p1().y() - slope1 * line1.p1().x();
qreal b2 = line2.p1().y() - slope1 * line2.p1().x();
qreal x_overlap = (b2 - b1) / (slope1 - slope2);
if (x_overlap < qMin(line1.p1().x(), line1.p2().x()) ||
x_overlap > qMax(line1.p1().x(), line1.p2().x()) ||
x_overlap < qMin(line2.p1().x(), line2.p2().x()) ||
x_overlap > qMax(line2.p1().x(), line2.p2().x())) {
return false;
}
return true;
}
bool GetOverlapSegment(const QLineF& line1, const QLineF& line2, QLineF& overlap)
{
bool is_overlap = DoLineOverlapWithSameSlope(line1, line2);
if (!is_overlap) 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;
}