You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Processing(Python)图像不显示求助:嵌套循环绘制网格图形失败

问题分析与修复方案

你的代码存在两个核心问题导致无法显示图形:

1. 循环缩进错误

starty += scale 和 startx = 0 被放在外层for i循环的外面,导致:

  • 只有第一行的猫会被重复绘制5次
  • 后续行的猫从startx=400的位置开始绘制,完全超出画布范围

2. 缩放比例计算错误

你设置的scale = 400 / rows(值为80)会将猫放大80倍,原始猫的图形宽度约150像素,缩放后宽度达到12000像素,远远超出400x400的画布,即使位置正确也看不到任何内容。


修复后的代码

方案一:使用draw()循环绘制(适合动态更新场景)

def setup():
    size(400, 400) 
    background(255)  

def drawCat(x, y, s):
  pushMatrix()
  translate(x,y)
  scale(s)
  fill(210,125,45)
  ellipse(75,90, 100, 100)
  triangle(15,35,25,85,65,50)
  triangle(135,35,125,85,85,50)
  fill(0)
  rect(35,37, 80,10)
  fill(0)
  rect(50,7, 50,40)

  ellipse(45,80,20,20)
  ellipse(105,80,20,20)
  fill(255,192,203)
  triangle(75,90,65,105,85,105)
  popMatrix()

def draw():
    background(255)  # 每次绘制前清空画布,避免重叠
    startx = 0
    starty = 0
    rows = 5
    cell_size = 400 / rows  # 每个网格单元的尺寸
    scale_factor = cell_size / 150  # 按猫的原始宽度(约150px)缩放,适配网格
    for i in range(rows):
        for j in range(rows):
            drawCat(startx, starty, scale_factor)
            startx += cell_size
        # 每行绘制完成后,重置x坐标,下移y坐标
        starty += cell_size
        startx = 0

方案二:移到setup()中一次性绘制(更高效,适合静态图形)

因为你的图形是静态的,不需要动态更新,可以把绘制逻辑放到setup()里,避免draw()循环重复执行:

def setup():
    size(400, 400) 
    background(255)  
    startx = 0
    starty = 0
    rows = 5
    cell_size = 400 / rows
    scale_factor = cell_size / 150
    for i in range(rows):
        for j in range(rows):
            drawCat(startx, starty, scale_factor)
            startx += cell_size
        starty += cell_size
        startx = 0

def drawCat(x, y, s):
  pushMatrix()
  translate(x,y)
  scale(s)
  fill(210,125,45)
  ellipse(75,90, 100, 100)
  triangle(15,35,25,85,65,50)
  triangle(135,35,125,85,85,50)
  fill(0)
  rect(35,37, 80,10)
  fill(0)
  rect(50,7, 50,40)

  ellipse(45,80,20,20)
  ellipse(105,80,20,20)
  fill(255,192,203)
  triangle(75,90,65,105,85,105)
  popMatrix()

def draw():
    # 空函数,避免重复绘制
    pass

内容的提问来源于stack exchange,提问作者bellacaprino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 04:07:05