【问题标题】:Pixel color calculation 255 to 0像素颜色计算 255 到 0
【发布时间】:2011-11-29 17:39:58
【问题描述】:

我一直在使用微软here的算法:

INT iWidth = bitmap.GetWidth();
INT iHeight = bitmap.GetHeight();
Color color, colorTemp;
for(INT iRow = 0; iRow < iHeight; iRow++)
{
   for(INT iColumn = 0; iColumn < iWidth; iColumn++)
   {
      bitmap.GetPixel(iColumn, iRow, &color);
      colorTemp.SetValue(color.MakeARGB(
         (BYTE)(255 * iColumn / iWidth), 
         color.GetRed(),
         color.GetGreen(),
         color.GetBlue()));
      bitmap.SetPixel(iColumn, iRow, colorTemp);
   }
}

创建渐变 alpha 混合。他们的从左到右,我需要一个从下到上的,所以我改变了他们的路线

(BYTE)(255 * iColumn / iWidth)

(BYTE)(255 - ((iRow * 255) / iHeight))

这使得第 0 行的 alpha 值为 255,直到最后一行的 alpha 值为 8。

如何更改计算以使 alpha 从 255 变为 0(而不是 255 到 8)?

【问题讨论】:

    标签: c++ math colors gdi+


    【解决方案1】:

    f(x) = 255 * (x - 8) / (255 - 8)?

    其中 x 在 [8, 255] 中,f(x) 在 [0, 255] 中

    最初的问题可能与这样一个事实有关,即如果宽度为 100 并且迭代水平像素,则只会得到 0 到 99 的值。因此,99 除以 100 永远不会是 1。你需要的是类似255*(column+1)/width

    【讨论】:

      【解决方案2】:
      (BYTE)( 255 - 255 * iRow / (iHeight-1) )
      

      iRow 介于 0(iHeight-1) 之间,所以如果我们想要一个介于 0 和 1 之间的值,我们需要除以 (iHeight-1)。我们实际上想要一个介于 0 和 255 之间的值,所以我们只需按比例放大 255。最后我们希望从最大值开始下降到最小值,所以我们只需从 255 中减去该值。

      在端点:

      iRow = 0
          255 - 255 * 0 / (iHeight-1) = 255
      iRow = (iHeight-1)
          255 - 255 * (iHeight-1) / (iHeight-1) = 255 - 255 * 1 = 0
      

      请注意,iHeight 必须大于或等于 2 才能工作(如果为 1,您将得到除以零)。

      编辑: 这将导致只有最后一行的 alpha 值为 0。您可以使用

      获得更均匀的 alpha 值分布
      (BYTE)( 255 - 256 * iRow / iHeight )
      

      但是,如果 iHeight 小于 256,则最后一行的 alpha 值不会为 0。

      【讨论】:

        【解决方案3】:

        尝试使用以下计算之一(它们给出相同的结果):

        (BYTE)(255 - (iRow * 256 - 1) / (iHeight - 1))
        (BYTE)((iHeight - 1 - iRow) * 256 - 1) / (iHeight - 1))
        

        这仅在使用有符号除法时才有效(您使用的类型 INT 似乎与 int 相同,所以它应该有效)。

        【讨论】:

          猜你喜欢
          • 2018-03-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多