Qt 计算两条直线QLineF的重叠部分,如何存在则返回该直线

计算两条直线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;
}
相关推荐
xiaosannihaiyl249 分钟前
Scala语言的函数实现
开发语言·后端·golang
新手小袁_J26 分钟前
java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigur
java·开发语言·spring·spring cloud·bootstrap·maven·mybatis
墨鸦_Cormorant27 分钟前
Java 创建图形用户界面(GUI)组件详解之下拉式菜单(JMenu、JMenuItem)、弹出式菜单(JPopupMenu)等
java·开发语言·gui
cccccc语言我来了27 分钟前
c++-----------------多态
java·开发语言·c++
南鸢1.029 分钟前
11张思维导图带你快速学习java
java·开发语言
sunny-ll31 分钟前
【C++】explicit关键字详解(explicit关键字是什么? 为什么需要explicit关键字? 如何使用explicit 关键字)
c语言·开发语言·c++·算法·面试
泯泷32 分钟前
JS代码混淆器:JavaScript obfuscator 让你的代码看起来让人痛苦
开发语言·javascript·ecmascript
轩源源35 分钟前
C++草原三剑客之一:继承
开发语言·数据结构·c++·算法·青少年编程·继承·组合
未知陨落41 分钟前
leetcode题目(1)
c++·leetcode
每天写点bug3 小时前
【go每日一题】 责任链模式的实现
开发语言·golang·责任链模式