首页 > 解决方案 > 垂直梯度公式

问题描述

我想编写一个生成1000x1000 .ppm文件的 C 程序,显示从黑色(左)到白色(右)的垂直渐变。现在,如果图片会256x256很容易:

P3
256 256
255
0 0 0 1 1 1 2 2 2 .... 255 255 255
0 0 0 1 1 1 2 2 2 .... 255 255 255
.
.
.
0 0 0 1 1 1 2 2 2 .... 255 255 255

问题是,因为它必须是 1000x1000(超过 255),我不确定我应该遵循什么公式来获得完美的渐变。有任何想法吗?

标签: cmathppm

解决方案


您可以按所需的总宽度缩放像素的颜色索引,以生成 0 到 1 之间的小数,表示其在行中的标准化位置。然后乘以 256 以将其缩放到颜色范围。这给出了:

int color = (float)offset / width * 256;

可运行的概念证明:

const makeGradient = (gradEl, width=500, height=500) => {
  let html = "";
  
  for (let offset = 0; offset < width; offset++) {
    const color = offset / width * 256; // JS does float division
    html += `
      <div style="
        background-color: rgb(${color}, ${color}, ${color});
        width: 1px; height: ${height}px;
      "></div>
    `;
  }
  
  gradEl.innerHTML = html;
};

const gradEl = document.querySelector("#gradient");
makeGradient(gradEl);
document.querySelector("input")
  .addEventListener("keyup", e => {
    makeGradient(gradEl, +e.target.value || null);
  });
body {
  background: blue;
}

#gradient {
  display: flex;
}
<input value="500" type="number" min="0" max="2000">
<div id="gradient"></div>


推荐阅读