c - 垂直梯度公式
问题描述
我想编写一个生成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),我不确定我应该遵循什么公式来获得完美的渐变。有任何想法吗?
解决方案
您可以按所需的总宽度缩放像素的颜色索引,以生成 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>
推荐阅读
- android - 我们如何获取传递给 WorkManager WorkRequest 的数据?
- ios - 如何将存储属性添加到 Swift 结构扩展
- android - 在 Android 11 上从“/apex/com.android.runtime/lib64/bionic/libc.so”中止崩溃
- nullpointerexception - 杰克逊解析json中缺少字段时出错java.lang.NullPointerException
- python - python pandas groupby eventType和eventId并获取每个eventType之间的日期差异
- azure - 保护访问以触发 Azure 逻辑应用(HTTP 请求触发器)
- c# - 字符串到字节数组到文件以用于 POST 请求
- google-cloud-sql - 如何从 Cloud Build 连接到 Cloud SQL 以运行 knex 数据库迁移?
- graphql - GraphQL 多值 eq 过滤器
- java - Keycloak 和 SSL 连接在运行模式下工作,在测试模式下失败