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

如何在Processing中将500×500二维数组渲染到200×200网格?

500×500数组渲染到200×200屏幕网格的实现方案

要将500×500的二维数组缩小渲染到200×200的屏幕网格,核心是通过降采样将大数组的多组元素映射到单个屏幕像素上,以下是两种实用的实现方式:

一、最近邻采样(快速简洁)

这种方法直接取屏幕像素对应大数组区域中最接近的元素值,计算量小,适合像素风格的内容渲染。

修改后的Processing代码:

void render() {
  loadPixels();
  int bigWidth = 500;
  int bigHeight = 500;
  // 计算大数组到屏幕网格的缩放比例
  float scaleX = (float)bigWidth / width;
  float scaleY = (float)bigHeight / height;

  for (int x = 0; x < width; x++) {
    for (int y = 0; y < height; y++) {
      // 计算对应大数组的坐标(四舍五入取最近的点)
      int bigX = Math.round(x * scaleX);
      int bigY = Math.round(y * scaleY);
      // 确保坐标不超出大数组边界
      bigX = constrain(bigX, 0, bigWidth - 1);
      bigY = constrain(bigY, 0, bigHeight - 1);
      
      int pixelIndex = y * width + x;
      float value = bigArray[bigX][bigY]; // bigArray是你的500×500数组
      pixels[pixelIndex] = color(value*RMULT, value*GMULT, value*BMULT);
    }
  }
  updatePixels();
}

二、平均采样(平滑无锯齿)

如果需要更平滑的渲染效果,可计算屏幕像素对应大数组区域内所有元素的平均值,用平均值生成颜色,能有效减少锯齿感。

修改后的Processing代码:

void render() {
  loadPixels();
  int bigWidth = 500;
  int bigHeight = 500;
  float scaleX = (float)bigWidth / width;
  float scaleY = (float)bigHeight / height;

  for (int x = 0; x < width; x++) {
    for (int y = 0; y < height; y++) {
      // 计算当前屏幕像素对应的大数组区域范围
      float startX = x * scaleX;
      float endX = (x + 1) * scaleX;
      float startY = y * scaleY;
      float endY = (y + 1) * scaleY;

      float totalValue = 0;
      int sampleCount = 0;
      // 遍历区域内所有大数组元素
      for (int bigX = (int)Math.floor(startX); bigX < Math.ceil(endX); bigX++) {
        for (int bigY = (int)Math.floor(startY); bigY < Math.ceil(endY); bigY++) {
          // 边界校验,避免数组越界
          if (bigX >= 0 && bigX < bigWidth && bigY >=0 && bigY < bigHeight) {
            totalValue += bigArray[bigX][bigY];
            sampleCount++;
          }
        }
      }
      // 计算区域内元素的平均值
      float avgValue = totalValue / sampleCount;
      
      int pixelIndex = y * width + x;
      pixels[pixelIndex] = color(avgValue*RMULT, avgValue*GMULT, avgValue*BMULT);
    }
  }
  updatePixels();
}

注意事项

  • 替换代码中的bigArray为你实际的500×500二维数组变量名;
  • 最近邻采样速度更快,平均采样视觉效果更平滑,可根据需求选择;
  • 所有数组坐标的边界校验不可省略,否则会触发数组索引越界异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 15:41:13