[Python dxfgrabber+matplotlib] Display the .dxf format file exported by AutoCAD

code:

import dxfgrabber,matplotlib
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon

matplotlib.use('TkAgg')

# 使用 dxfgrabber 库加载 DXF 文件
drawing = dxfgrabber.readfile('files/Main board0.DXF')

# 创建 Matplotlib 图形
fig, ax = plt.subplots()

# 遍历图形中的实体
for entity in drawing.entities:
    if entity.dxftype == 'LWPOLYLINE':
        vertex_list = entity.points  # 获取多段线的顶点坐标
        if entity.is_closed:  # 判断多段线是否闭合
            vertex_list.append(vertex_list[0])  # 闭合多段线
        # 创建多边形并添加到绘图区域
        polygon = Polygon(vertex_list, closed=True, edgecolor='black', facecolor='none')
        ax.add_patch(polygon)
    elif entity.dxftype == 'LINE':
        x1, y1, _ = entity.start
        x2, y2, _ = entity.end
        ax.plot([x1, x2], [y1, y2], 'b-')
    elif entity.dxftype == 'TEXT':
        x, y, _ = entity.insert  # 获取插入点坐标
        text = entity.text
        ax.text(x, y, text, fontsize=8, verticalalignment='center', horizontalalignment='center')
    elif entity.dxftype == 'SOLID':
        vertex_list = [(vertex[0], vertex[1]) for vertex in entity.points]  # 获取多边形顶点坐标
        # polygon = Polygon(vertex_list, closed=True, edgecolor='gray', facecolor='none')
        polygon = plt.Polygon(xy=vertex_list, color='gray', alpha=0.8)
        ax.add_patch(polygon)

# 获取图形的范围信息
extmin = drawing.header.get('$LIMMIN')
extmax = drawing.header.get('$LIMMAX')
print(extmax,extmin)

# 设置绘图区域范围
ax.set_xlim(extmin[0], extmax[0])
ax.set_ylim(extmin[1], extmax[1])

# 显示图形
plt.gca().set_aspect('equal', adjustable='box')  # 设置等比例显示
plt.xlabel('X')
plt.ylabel('Y')
plt.grid(True)
plt.title('DXF Drawing with Matplotlib')
plt.show()

Effect:

Another way:

[Python ezdxf+matplotlib] Display the .dxf format file exported by AutoCAD_Zhichao_97's Blog-CSDN Blog

おすすめ

転載: blog.csdn.net/ChaoChao66666/article/details/132324784