...
嵌入式

c语言颜色处理函数分享

多看别人代码绝对是有好处的,千万不要闭门造车...

今天通过翻阅ws2812FX库看到了几个好用的函数,分享一下.

一、颜色生成(输入0-255生成r-g-b的颜色)

/**
 * @brief 混合生成
 * @param pos 输入 0-255  提取颜色
 * @return uint32_t
 */
uint32_t Color_Wheel(uint8_t pos) {
  pos = 255 - pos;
  if(pos < 85) {
    return ((uint32_t)(255 - pos * 3) << 16) | ((uint32_t)(0) << 8) | (pos * 3);
  } else if(pos < 170) {
    pos -= 85;
    return ((uint32_t)(0) << 16) | ((uint32_t)(pos * 3) << 8) | (255 - pos * 3);
  } else {
    pos -= 170;
    return ((uint32_t)(pos * 3) << 16) | ((uint32_t)(255 - pos * 3) << 8) | (0);
  }
}

挺好的 我顺便转成了js的

function Color_Wheel(pos) {
  pos = 255 - pos;
  if(pos < 85) {
    return ((255 - pos * 3) << 16) | ((0) << 8) | (pos * 3);
  } else if(pos < 170) {
    pos -= 85;
    return ((0) << 16) | ((pos * 3) << 8) | (255 - pos * 3);
  } else {
    pos -= 170;
    return ((pos * 3) << 16) | ((255 - pos * 3) << 8) | (0);
  }
}
// 如果要输出16进制要
for (let index = 0; index < 256; index++) {
    var color = Color_Wheel(index)
     // 转成16进制字符串,补0到6位
    var c16 = color.toString(16).padStart(6,'0')
    console.log("■■■■■■:"+c16.toLocaleUpperCase(),'color: #'+c16+';')
}

二、颜色混合函数(给两个颜色,输入偏移生成两个颜色的混合颜色)

static uint8_t *blend(uint8_t *dest, uint8_t *src1, uint8_t *src2, uint16_t cnt, uint8_t blendAmt)
{
    if (blendAmt == 0)
    {
        memmove(dest, src1, cnt);
    }
    else if (blendAmt == 255)
    {
        memmove(dest, src2, cnt);
    }
    else
    {
        for (uint16_t i = 0; i < cnt; i++)
        {
            dest[i] = blendAmt * ((int)src2[i] - (int)src1[i]) / 256 + src1[i];
        }
    }
    return dest;
}

// 混合颜色
uint32_t Color_Blend(uint32_t color1, uint32_t color2, uint8_t blendAmt)
{
    uint32_t blendedColor;
    blend((uint8_t *)&blendedColor, (uint8_t *)&color1, (uint8_t *)&color2, sizeof(uint32_t), blendAmt);
    return blendedColor;
}

js版本

function blend(dest, src1, src2, cnt, blendAmt) {
    if (blendAmt === 0){
        dest.set(src1);
    }else if(blendAmt === 255) {
        // If blendAmt is 0 or 255, just copy src2 to dest
        dest.set(src2);
    } else {
        for (let i = 0; i < cnt; i++) {
            dest[i] = (blendAmt * (src2[i] - src1[i]) / 256) + src1[i];
        }
    }
    return dest;
}

/**
 * @brief 混合颜色
 * @param color1 输入 16进制颜色值 0x000000
 * @param color2 输入 16进制颜色值 0xffffff
 * @param blendAmt 输入 0-255  过渡偏移
 * @return uint32_t
 */
function Color_Blend(color1, color2, blendAmt) {
    const blendedColor = new Uint32Array(1);
    blend(new Uint8Array(blendedColor.buffer), new Uint8Array(Uint32Array.of(color1).buffer), new Uint8Array(Uint32Array.of(color2).buffer), 4, blendAmt);
    return blendedColor[0];
}

持续更新中...

奉加微phy6222 安信可PB系列蓝牙添加OTA升级功能 在线免费的AI照片无损放大和模糊修复工具分享
biu biu biu
css设置滚动条样式 electron创建圆角窗口附带阴影效果 electron 显示右键菜单 限制只对编辑框或选中文本显示右键菜单 js 返回并刷新 JavaScript 后退 刷新 electron 前端使用vue 或 webpack 打包一些问题整理