Skip to main content
 首页 » 编程设计

python之在图像上绘制对角线

2025年05月04日14xxx_UU

嗨,我正在尝试在图像的右上角到左下角绘制对角线,这是我目前的代码。

  width = getWidth(picture) 
  height = getHeight(picture) 
  for x in range(0, width): 
    for y in range(0, height): 
      pixel = getPixel(picture, x, y) 
      setColor(pixel, black) 

谢谢

请您参考如下方法:

大多数图形库都有一些方法可以直接画线。

在JES有 addLine 函数,所以你可以这样做

addLine(picture, 0, 0, width, height) 

如果您坚持设置单个像素,您应该看看 Bresenham Line Algorithm ,这是最有效的画线算法之一。

对您的代码的注释:您对两个嵌套循环所做的如下

for each column in the picture 
  for each row in the current column 
     set the pixel in the current column and current row to black 

所以基本上你用黑色像素填充了整个图像。

编辑

要在整个图像上绘制多条对角线(在它们之间留有空间),您可以使用以下循环

width = getWidth(picture) 
height = getHeight(picture) 
space = 10 
for x in range(0, 2*width, space): 
  addLine(picture, x, 0, x-width, height) 

这给你一个图像(这个例子是手绘的......)

这利用了大多数图形库提供的裁剪功能,即不在图像内的线条部分将被简单地忽略。请注意,如果没有 2*width(即如果 x 仅达到 with),则只会绘制线的左上半部分。 ..