```python
from pyautocad import Autocad, APoint, aDouble
import math
# 连接到AutoCAD实例
acad = Autocad(create_if_not_exists=True)
doc = acad.doc
# ========== 1. 绘制基本多段线 ==========
def draw_basic_polyline(points_list, color_index=7, lineweight=0.25):
"""
绘制基本多段线(仅由直线段组成)
参数:
points_list: 点坐标列表,格式如 [(x1,y1), (x2,y2), ...]
color_index: 颜色索引(1-255)
lineweight: 线宽(毫米)
返回:
多段线对象
"""
# 将点列表转换为pyautocad所需的格式
flattened_points = []
for point in points_list:
if isinstance(point, tuple) or isinstance(point, list):
if len(point) >= 2:
flattened_points.extend([point[0], point[1], 0]) # z坐标默认为0 [ref_1]
# 创建多段线对象
points_array = aDouble(flattened_points)
polyline_obj = acad.model.AddPolyLine(points_array) # [ref_1]
# 设置基本属性
polyline_obj.Color = color_index
polyline_obj.Lineweight = lineweight
return polyline_obj
# 示例1:绘制一个简单的四边形
quad_points = [
(0, 0),
(100, 0),
(100, 50),
(0, 50),
(0, 0) # 闭合多段线
]
quad_polyline = draw_basic_polyline(quad_points, color_index=3, lineweight=0.35)
print(f"已绘制四边形多段线,包含 {len(quad_points)} 个顶点")
# ========== 2. 设置多段线颜色(真彩色) ==========
def set_polyline_rgb_color(polyline_obj, red, green, blue):
"""
使用RGB值设置多段线颜色
参数:
polyline_obj: 多段线对象
red, green, blue: RGB颜色值(0-255)
"""
version = acad.Application.Version[:2] # 获取CAD版本号
clr = acad.Application.GetInterfaceObject(f"AutoCAD.AcCmColor.{version}")
clr.SetRGB(red, green, blue) # 设置RGB颜色 [ref_1]
polyline_obj.TrueColor = clr # 应用真彩色
# 示例2:绘制五角星并设置RGB颜色
star_points = [
(200, 0), # 点1
(240, 80), # 点2
(320, 80), # 点3
(260, 130), # 点4
(280, 210), # 点5
(200, 160), # 点6
(120, 210), # 点7
(140, 130), # 点8
(80, 80), # 点9
(160, 80), # 点10
(200, 0) # 闭合
]
star_polyline = draw_basic_polyline(star_points, color_index=1, lineweight=0.50)
set_polyline_rgb_color(star_polyline, 255, 165, 0) # 橙色
# ========== 3. 设置多段线段宽度(可变宽度) ==========
def set_polyline_segment_width(polyline_obj, segment_index, start_width, end_width):
"""
设置多段线特定段的宽度
参数:
polyline_obj: 多段线对象
segment_index: 段索引(从0开始)
start_width: 段起点宽度(毫米)
end_width: 段终点宽度(毫米)
"""
polyline_obj.SetWidth(segment_index, start_width, end_width) # [ref_1]
# 示例3:创建箭头形状的多段线(可变宽度)
arrow_points = [
(0, 100),
(80, 100),
(80, 120),
(120, 100),
(80, 80),
(80, 100)
]
arrow_polyline = draw_basic_polyline(arrow_points, color_index=5, lineweight=0.35)
# 设置箭头尾部和头部的不同宽度
set_polyline_segment_width(arrow_polyline, 0, 0.5, 0.5) # 第一段:恒定宽度
set_polyline_segment_width(arrow_polyline, 1, 0.5, 1.5) # 第二段:渐变宽度
set_polyline_segment_width(arrow_polyline, 2, 1.5, 3.0) # 第三段:箭头头部
set_polyline_segment_width(arrow_polyline, 3, 3.0, 1.5) # 第四段:箭头尾部
set_polyline_segment_width(arrow_polyline, 4, 1.5, 0.5) # 第五段:渐变回原宽度
# ========== 4. 创建含圆弧的多段线 ==========
def draw_polyline_with_arcs():
"""
创建包含圆弧段的多段线
使用AddPolyline创建的普通多段线只能包含直线段,
要包含圆弧需要使用轻量多段线(LightWeightPolyline)或不同的方法
"""
# 方法1:使用pywin32创建轻量多段线(支持圆弧)[ref_3]
try:
import pythoncom
import win32com.client
wincad = win32com.client.Dispatch("AutoCAD.Application")
doc_win = wincad.ActiveDocument
msp = doc_win.ModelSpace
# 定义点坐标(x,y,bulge)格式,bulge控制圆弧
# bulge = tan(包含角/4),正值为逆时针,负值为顺时针
points_with_bulge = [
0, 150, 0, # 点1,bulge=0(直线)
50, 150, 0, # 点2,bulge=0
100, 200, 0.5, # 点3,bulge=0.5(圆弧)
150, 150, 0, # 点4,bulge=0
200, 150, 0 # 点5,bulge=0
]
# 创建轻量多段线
lwpolyline = msp.AddLightWeightPolyline(points_with_bulge)
lwpolyline.Closed = True # 闭合多段线
lwpolyline.Color = 4 # 青色
print("已创建含圆弧的轻量多段线")
return lwpolyline
except Exception as e:
print(f"创建含圆弧多段线时出错: {e}")
return None
# 调用含圆弧的多段线绘制函数
arc_polyline = draw_polyline_with_arcs()
# ========== 5. 多段线高级属性设置 ==========
def set_advanced_polyline_properties(polyline_obj, properties_dict):
"""
设置多段线的高级属性
参数:
polyline_obj: 多段线对象
properties_dict: 属性字典,可包含:
- 'closed': 是否闭合
- 'constant_width': 恒定宽度
- 'elevation': 标高
- 'thickness': 厚度
- 'linetype': 线型
- 'layer': 图层
"""
if 'closed' in properties_dict:
polyline_obj.Closed = properties_dict['closed']
if 'constant_width' in properties_dict:
polyline_obj.ConstantWidth = properties_dict['constant_width']
if 'elevation' in properties_dict:
polyline_obj.Elevation = properties_dict['elevation']
if 'thickness' in properties_dict:
polyline_obj.Thickness = properties_dict['thickness']
if 'linetype' in properties_dict:
# 加载线型(如果未加载)
try:
doc.Linetypes.Load("DASHED", "acad.lin")
except:
pass
polyline_obj.Linetype = properties_dict['linetype']
if 'layer' in properties_dict:
polyline_obj.Layer = properties_dict['layer']
# 示例4:创建并设置高级属性的多段线
advanced_points = [
(300, 0),
(350, 50),
(400, 0),
(350, -50),
(300, 0)
]
advanced_polyline = draw_basic_polyline(advanced_points, color_index=2, lineweight=0.25)
# 设置高级属性
advanced_props = {
'closed': True,
'constant_width': 1.0, # 设置恒定宽度
'elevation': 10.0, # 设置标高
'thickness': 5.0, # 设置厚度(3D效果)
'linetype': 'DASHED', # 设置线型为虚线
'layer': 'Polyline_Layer'
}
set_advanced_polyline_properties(advanced_polyline, advanced_props)
# ========== 6. 批量创建多段线 ==========
def create_grid_polylines(start_x, start_y, rows, cols, cell_size, color_scheme='gradient'):
"""
创建网格状的多段线阵列
参数:
start_x, start_y: 起始坐标
rows, cols: 行数和列数
cell_size: 单元格大小
color_scheme: 颜色方案 ('gradient', 'alternate', 'rainbow')
返回:
多段线对象列表
"""
polylines = []
for row in range(rows):
for col in range(cols):
# 计算当前单元格的坐标
x = start_x + col * cell_size
y = start_y + row * cell_size
# 定义矩形多段线的四个顶点
points = [
(x, y),
(x + cell_size, y),
(x + cell_size, y + cell_size),
(x, y + cell_size),
(x, y) # 闭合
]
# 根据颜色方案设置颜色
if color_scheme == 'gradient':
color_index = 1 + (row + col) % 7 # 渐变颜色
elif color_scheme == 'alternate':
color_index = 1 if (row + col) % 2 == 0 else 3 # 交替颜色
elif color_scheme == 'rainbow':
color_index = 1 + (row * 3 + col) % 7 # 彩虹色
else:
color_index = 7 # 默认白色
# 创建多段线
polyline = draw_basic_polyline(points, color_index=color_index, lineweight=0.18)
# 设置线宽渐变效果
for i in range(4): # 4个线段
width_factor = (i + row + col) % 3
start_width = 0.1 + width_factor * 0.1
end_width = 0.1 + ((width_factor + 1) % 3) * 0.1
set_polyline_segment_width(polyline, i, start_width, end_width)
polylines.append(polyline)
return polylines
# 示例5:创建网格多段线
grid_polylines = create_grid_polylines(
start_x=0,
start_y=250,
rows=3,
cols=4,
cell_size=60,
color_scheme='rainbow'
)
print(f"已创建 {len(grid_polylines)} 个网格多段线")
# ========== 7. 多段线编辑与查询 ==========
def get_polyline_info(polyline_obj):
"""
获取多段线的详细信息
参数:
polyline_obj: 多段线对象
返回:
包含多段线信息的字典
"""
info = {
'顶点数': polyline_obj.NumberOfVertices,
'是否闭合': polyline_obj.Closed,
'面积': polyline_obj.Area if hasattr(polyline_obj, 'Area') else 'N/A',
'长度': polyline_obj.Length if hasattr(polyline_obj, 'Length') else 'N/A',
'颜色': polyline_obj.Color,
'线宽': polyline_obj.Lineweight,
'图层': polyline_obj.Layer,
'线型': polyline_obj.Linetype
}
# 获取顶点坐标
vertices = []
for i in range(polyline_obj.NumberOfVertices):
try:
coord = polyline_obj.Coordinate(i)
vertices.append((coord[0], coord[1]))
except:
vertices.append(('N/A', 'N/A'))
info['顶点坐标'] = vertices
return info
# 查询示例多段线的信息
polyline_info = get_polyline_info(quad_polyline)
print("\n四边形多段线信息:")
for key, value in polyline_info.items():
if key != '顶点坐标':
print(f" {key}: {value}")
print(f" 顶点坐标: {polyline_info['顶点坐标']}")
# ========== 8. 实用函数:绘制复杂图形 ==========
def draw_gear_profile(center_x, center_y, radius, teeth_count, tooth_height, color_index=7):
"""
绘制齿轮轮廓的多段线
参数:
center_x, center_y: 中心坐标
radius: 基圆半径
teeth_count: 齿数
tooth_height: 齿高
color_index: 颜色索引
返回:
齿轮轮廓多段线对象
"""
points = []
angle_step = 2 * math.pi / teeth_count
for i in range(teeth_count * 2):
angle = i * angle_step / 2
if i % 2 == 0: # 齿顶
r = radius + tooth_height
else: # 齿根
r = radius - tooth_height * 0.3
x = center_x + r * math.cos(angle)
y = center_y + r * math.sin(angle)
points.append((x, y))
# 闭合图形
points.append(points[0])
# 创建多段线
gear_polyline = draw_basic_polyline(points, color_index=color_index, lineweight=0.35)
gear_polyline.Closed = True
return gear_polyline
# 示例6:绘制齿轮轮廓
gear_polyline = draw_gear_profile(
center_x=500,
center_y=100,
radius=40,
teeth_count=12,
tooth_height=8,
color_index=6
)
# ========== 9. 显示与优化 ==========
# 启用线宽显示
doc.preferences.LineweightDisplay = 1 # [ref_1]
# 刷新显示
acad.Application.Update() # [ref_1]
acad.Application.ZoomAll() # [ref_1]
# 在AutoCAD命令行显示信息
acad.prompt("\n多段线绘制完成!\n")
acad.prompt("========================================\n")
acad.prompt("已绘制以下多段线:\n")
acad.prompt("1. 四边形多段线(绿色,0.35mm)\n")
acad.prompt("2. 五角星多段线(橙色,0.50mm)\n")
acad.prompt("3. 箭头多段线(蓝色,可变宽度)\n")
acad.prompt("4. 高级属性多段线(黄色,虚线)\n")
acad.prompt("5. 网格多段线阵列(彩虹色)\n")
acad.prompt("6. 齿轮轮廓多段线(洋红色)\n")
acad.prompt("========================================\n")
# ========== 10. 总结与最佳实践 ==========
print("=" * 70)
print("Python在AutoCAD中绘制多段线的完整指南")
print("=" * 70)
print("\n一、基本绘制方法总结:")
print("1. 使用 AddPolyLine() 方法创建多段线 [ref_1]")
print("2. 点坐标需要转换为 aDouble 格式 [ref_1]")
print("3. 基本属性设置:Color, Lineweight, Layer")
print("\n二、颜色设置技巧:")
print("| 方法 | 代码示例 | 特点 |")
print("|------|----------|------|")
print("| 索引颜色 | polyline.Color = 1 | 简单快速 |")
print("| 真彩色 | clr.SetRGB(255,0,0) | 精确控制 [ref_1] |")
print("\n三、线宽控制方法:")
print("1. 恒定线宽:polyline.ConstantWidth = 线宽值")
print("2. 可变线宽:polyline.SetWidth(段索引, 起点宽, 终点宽) [ref_1]")
print("3. 显示线宽:doc.preferences.LineweightDisplay = 1 [ref_1]")
print("\n四、多段线类型对比:")
print("| 类型 | 创建方法 | 特点 | 适用场景 |")
print("|------|----------|------|----------|")
print("| 普通多段线 | AddPolyLine() | 直线段组成 | 简单多边形 |")
print("| 轻量多段线 | AddLightWeightPolyline