代码:
import ezdxf,matplotlib
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
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:
# 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-')
if 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)
# 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 board0.dxf"
display_dxf(file_path)
效果: