不想加载geos库,故使用qt的方法,计算出矩形与线段的交集。
QLineF clipLine(QLineF line, QRectF box) { QRectF lineBox(line.p1(), line.p2()); if (!box.intersects(lineBox)) { return line; } bool b0 = box.contains(line.p1()); bool b1 = box.contains(line.p2()); if (b0 && b1) { return line; } else { QLineF line1(box.topLeft(), box.topRight()); QLineF line2(box.topRight(), box.bottomRight()); QLineF line3(box.bottomLeft(), box.bottomRight()); QLineF line4(box.topLeft(), box.bottomLeft()); QPointF pt1, pt2, pt3, pt4; bool bi1 = QLineF::BoundedIntersection == line.intersect(line1, &pt1); bool bi2 = QLineF::BoundedIntersection == line.intersect(line2, &pt2); bool bi3 = QLineF::BoundedIntersection == line.intersect(line3, &pt3); bool bi4 = QLineF::BoundedIntersection == line.intersect(line4, &pt4); if (b0) { if (bi1) return QLineF(line.p1(), pt1); if (bi2) return QLineF(line.p1(), pt2); if (bi3) return QLineF(line.p1(), pt3); if (bi4) return QLineF(line.p1(), pt4); } else if (b1) { if (bi1) return QLineF(line.p2(), pt1); if (bi2) return QLineF(line.p2(), pt2); if (bi3) return QLineF(line.p2(), pt3); if (bi4) return QLineF(line.p2(), pt4); } else { QPolygonF pts; if (bi1) pts.append(pt1); if (bi2) pts.append(pt2); if (bi3) pts.append(pt3); if (bi4) pts.append(pt4); return QLineF(pts.first(), pts.last()); } } }