12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- import ezdxf
- import math
- # 创建一个新的 DXF 文档
- doc = ezdxf.new()
- msp = doc.modelspace()
- # 定义四边形的四个顶点(这里是一个简单的矩形)
- points = [
- (0, 0), # 左下角
- (10, 0), # 右下角
- (10, 5), # 右上角
- (0, 5), # 左上角
- (0, 0) # 闭合多边形,回到起点
- ]
- # 创建一个多边形(PLINE,多段线)来表示四边形的边界(这一步是可选的,只是为了可视化)
- # boundary = msp.add_lwpolyline(points, close=True)
- # boundary.rgb = (254, 254, 254) # 设置为白色,以便与填充颜色对比(可选)
- # 创建填充图案(HATCH)
- hatch = msp.add_hatch()
- # 设置填充图案的类型(例如,SOLID 表示实体填充)
- hatch.dxf.pattern_name = "SOLID"
- # 设置填充图案的颜色为 RGB(255, 0, 0),即红色
- hatch.rgb = (128, 0, 0)
- # 添加填充边界(使用之前创建的多边形的顶点)
- # 注意:ezdxf 要求边界是由一系列闭合的、共面的、非自交的环组成的
- # 在这里,我们只有一个简单的四边形,所以只添加一个环
- hatch_boundary_paths = [(point[0], point[1], 0.0) for point in points[:-1]] # 转换为三维点,但 Z 坐标为 0
- edge_path = hatch.paths.add_edge_path()
- for i in range(3):
- edge_path.add_line(hatch_boundary_paths[i], hatch_boundary_paths[i + 1])
- edge_path.add_line(hatch_boundary_paths[-1], hatch_boundary_paths[0])
- # 保存 DXF 文件
- doc.saveas("filled_rectangle.dxf")
|