代码:
import ezdxf,matplotlib
import matplotlib.pyplot as plt
matplotlib.use('TkAgg') # 避免Matplotlib版本与其他相关库的兼容性问题
def display_dxf(file_path):
doc = ezdxf.readfile(file_path)
msp = doc.modelspace() # 获取DXF文档的模型空间
# for entity in msp: # 迭代模型空间中的实体
# print(entity) # 打印实体信息
fig, ax = plt.subplots()
for entity in msp:
print(entity,type(entity))
if entity.dxftype() == 'LINE':
start_point = entity.dxf.start
end_point = entity.dxf.end
ax.plot([start_point[0], end_point[0]], [start_point[1], end_point[1]], 'b-')
elif entity.dxftype() == 'LWPOLYLINE':
points = list(entity.get_points('xy')) # [(59.44499922, 76.43999952, 0.0, 0.0, 0.0), (59.44499922, 78.5400004, 0.0, 0.0, 0.0)]
x, y = zip(*points)
ax.plot(x, y, 'r-')
elif entity.dxftype() == 'CIRCLE':
center = entity.dxf.center
radius = entity.dxf.radius
circle = plt.Circle(center, radius, color='g', fill=False)
ax.add_patch(circle)
elif entity.dxftype() == 'TEXT':
insertion_point = entity.dxf.insert
text = entity.dxf.text
ax.text(insertion_point[0], insertion_point[1], text, fontsize=8)
elif entity.dxftype() == 'SOLID':
# 获取SOLID的四个角点的坐标
vtx0 = entity.dxf.vtx0
vtx1 = entity.dxf.vtx1
vtx2 = entity.dxf.vtx2
vtx3 = entity.dxf.vtx3
vertices = [(vtx0.x, vtx0.y), (vtx1.x, vtx1.y), (vtx2.x, vtx2.y), (vtx3.x, vtx3.y)]
vertices_list = []
for vertice in vertices:
vertices_list.append([round(vertice[0], 1), round(vertice[1], 1)])
# print(vertices_list)
polygon = plt.Polygon(xy=vertices_list, color='gray', alpha=0.8)
ax.add_patch(polygon)
# if entity.dxftype() == 'INSERT':
# block = doc.blocks[entity.dxf.name]
# for e in block:
# if e.dxftype() == 'LWPOLYLINE':
# points = list(e.get_points('xy'))
# x, y = zip(*points)
# ax.plot(x, y, 'r-')
# elif e.dxftype() == 'LINE':
# start_point = e.dxf.start
# end_point = e.dxf.end
# ax.plot([start_point[0], end_point[0]], [start_point[1], end_point[1]], 'b-')
# elif e.dxftype() == 'CIRCLE':
# center = e.dxf.center
# radius = e.dxf.radius
# circle = plt.Circle(center, radius, color='g', fill=False)
# ax.add_patch(circle)
# # elif e.dxftype() == 'SOLID':
# # points = [(e.dxf.points[i], e.dxf.points[i + 1]) for i in range(0, 8, 2)]
# # x, y = zip(*points)
# # ax.add_patch(Polygon(points, closed=True, edgecolor='m', facecolor='none'))
ax.set_aspect('equal', adjustable='box')
plt.xlabel('X')
plt.ylabel('Y')
plt.title('DXF Display')
plt.grid(True)
plt.show()
if __name__ == "__main__":
file_path = "files/Main board2007.dxf"
display_dxf(file_path)
效果:
另一种解决办法:
【Python dxfgrabber+matplotlib】显示AutoCAD导出的.dxf格式文件_Zhichao_97的博客-CSDN博客