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;
}
相关推荐
hummhumm13 分钟前
Oracle 第29章:Oracle数据库未来展望
java·开发语言·数据库·python·sql·oracle·database
wainyz23 分钟前
Java NIO操作
java·开发语言·nio
喵叔哟31 分钟前
重构代码之用委托替代继承
开发语言·重构
lzb_kkk37 分钟前
【JavaEE】JUC的常见类
java·开发语言·java-ee
SEEONTIME37 分钟前
python-24-一篇文章彻底掌握Python HTTP库Requests
开发语言·python·http·http库requests
Zfox_37 分钟前
【Linux】进程信号全攻略(二)
linux·运维·c语言·c++
起名字真南1 小时前
【OJ题解】C++实现字符串大数相乘:无BigInteger库的字符串乘积解决方案
开发语言·c++·leetcode
少年负剑去1 小时前
第十五届蓝桥杯C/C++B组题解——数字接龙
c语言·c++·蓝桥杯
cleveryuoyuo1 小时前
AVL树的旋转
c++
tyler_download1 小时前
golang 实现比特币内核:实现基于椭圆曲线的数字签名和验证
开发语言·数据库·golang