写个直线加粗的python
时间: 2023-06-21 07:14:57 浏览: 96
以下是一个简单的实现方法:
```python
def draw_line(x1, y1, x2, y2, thickness):
"""
在坐标系中画一条直线,可以设置线条粗细
:param x1: 起点x坐标
:param y1: 起点y坐标
:param x2: 终点x坐标
:param y2: 终点y坐标
:param thickness: 线条粗细
"""
if x1 == x2: # 如果是竖直线,则直接画矩形
rect = pygame.Rect(x1 - thickness // 2, y1, thickness, abs(y2 - y1))
elif y1 == y2: # 如果是水平线,则直接画矩形
rect = pygame.Rect(x1, y1 - thickness // 2, abs(x2 - x1), thickness)
else: # 计算斜率和偏移量
k = (y2 - y1) / (x2 - x1)
b = y1 - k * x1
# 计算线段两端点的坐标
x_left = min(x1, x2)
x_right = max(x1, x2)
y_bottom = min(y1, y2)
y_top = max(y1, y2)
# 画矩形
if abs(k) < 1: # 线斜率较小,以x为基准画矩形
for x in range(x_left, x_right + 1):
y = round(k * x + b)
rect = pygame.Rect(x - thickness // 2, y - thickness // 2, thickness, thickness)
pygame.draw.rect(screen, BLACK, rect)
else: # 线斜率较大,以y为基准画矩形
for y in range(y_bottom, y_top + 1):
x = round((y - b) / k)
rect = pygame.Rect(x - thickness // 2, y - thickness // 2, thickness, thickness)
pygame.draw.rect(screen, BLACK, rect)
```
这个函数使用了pygame库,在坐标系中画一条直线,并且可以设置线条粗细。如果是水平或竖直线,直接画矩形;如果是斜线,则先计算斜率和偏移量,再根据线段两端点的坐标画矩形。
阅读全文