【Python dxfgrabber+matplotlib】显示AutoCAD导出的.dxf格式文件

代码:

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()

效果:

另一种办法:

【Python ezdxf+matplotlib】显示AutoCAD导出的.dxf格式文件_Zhichao_97的博客-CSDN博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Zhichao_97

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值