如何在AutoCAD绘图中使新对象置于旧对象下方并处理重叠
用Shapely实现AutoCAD线条的遮挡效果
我通过Python的win32com库操作AutoCAD,先创建了一个闭合线条对象,再创建了一条穿过它的直线。现在需要拆分这条直线,移除和闭合对象重叠的部分,让闭合对象看起来遮挡住直线。
原始代码
import win32com.client import pythoncom acad = win32com.client.Dispatch("AutoCAD.Application") ms = acad.ActiveDocument.ModelSpace doc = acad.ActiveDocument obj_1 = [[0.09, 0.98, 0.13, 0.98, 0.17, 0.97, 0.2, 0.94, 0.2, 0.91, 0.17, 0.88, 0.13, 0.87, 0.09, 0.87, 0.05, 0.88, 0.02, 0.91, 0.02, 0.94, 0.05, 0.97, 0.09, 0.98]] obj_2 = [[0.1, 0.77, 0.2, 1.07]] def create_lines(coords): for line_coords in coords: for i in range(0, len(line_coords)-2, 2): x1, y1 = line_coords[i], line_coords[i+1] x2, y2 = line_coords[i+2], line_coords[i+3] ms.AddLine(APoint(x1, y1), APoint(x2, y2)) create_lines(obj_1) create_lines(obj_2)
当前效果

基于Shapely的解决方案
步骤说明
- 把AutoCAD中的线条坐标转换为Shapely的几何对象(多边形、直线)
- 用Shapely的
difference方法计算直线减去多边形的部分,自动拆分线段 - 在AutoCAD中重新绘制拆分后的线段
完整实现代码
先安装依赖:
pip install shapely pywin32
修改后的代码:
import win32com.client import pythoncom from shapely.geometry import LineString, Polygon # 定义AutoCAD的APoint辅助函数 def APoint(x, y, z=0): return win32com.client.VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_R8, (x, y, z)) acad = win32com.client.Dispatch("AutoCAD.Application") ms = acad.ActiveDocument.ModelSpace doc = acad.ActiveDocument # 原始坐标 obj_1_coords = [[0.09, 0.98, 0.13, 0.98, 0.17, 0.97, 0.2, 0.94, 0.2, 0.91, 0.17, 0.88, 0.13, 0.87, 0.09, 0.87, 0.05, 0.88, 0.02, 0.91, 0.02, 0.94, 0.05, 0.97, 0.09, 0.98]] obj_2_coords = [[0.1, 0.77, 0.2, 1.07]] def create_lines(coords): for line_coords in coords: for i in range(0, len(line_coords)-2, 2): x1, y1 = line_coords[i], line_coords[i+1] x2, y2 = line_coords[i+2], line_coords[i+3] ms.AddLine(APoint(x1, y1), APoint(x2, y2)) # 创建第一个闭合对象 create_lines(obj_1_coords) # 转换坐标为Shapely几何对象 # 闭合多边形 poly_points = [tuple(obj_1_coords[0][i:i+2]) for i in range(0, len(obj_1_coords[0]), 2)] polygon = Polygon(poly_points) # 原始直线 line_points = [tuple(obj_2_coords[0][i:i+2]) for i in range(0, len(obj_2_coords[0]), 2)] original_line = LineString(line_points) # 计算差集,得到拆分后的线段 split_result = original_line.difference(polygon) # 在AutoCAD中绘制拆分后的线段 if split_result.geom_type == 'LineString': coords = list(split_result.coords) ms.AddLine(APoint(coords[0][0], coords[0][1]), APoint(coords[1][0], coords[1][1])) elif split_result.geom_type == 'MultiLineString': for line in split_result.geoms: coords = list(line.coords) ms.AddLine(APoint(coords[0][0], coords[0][1]), APoint(coords[1][0], coords[1][1]))
关键点
- Shapely的
difference方法会自动处理直线与多边形的重叠,返回不重叠的线段部分 - 需要处理差集返回的是单个线段(LineString)还是多个线段(MultiLineString)的情况
- 确保
APoint函数正确定义,否则无法向AutoCAD传递坐标参数
内容的提问来源于stack exchange,提问作者Bobby Lith
相关产品推荐
相关产品推荐

