开发者

Pixel color calculation 255 to 0

开发者 https://www.devze.com 2023-04-09 22:00 出处:网络
I have been using the algorithm from Microsoft here: INT iWidth = bitmap.GetWidth(); INT iHeight = bitmap.GetHeight();

I have been using the algorithm from Microsoft 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);
   }
}

to create a gradient alpha blend. Theirs goes left to right, I need one going from bottom to top, so I changed their line

(BYTE)(255 * iColumn / iWidth)

to

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

This makes row 0 have alpha 2开发者_运维百科55, through to the last row having alpha 8.

How can I alter the calculation to make the alpha go from 255 to 0 (instead of 255 to 8)?


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

Where x is in [8, 255] and f(x) is in [0, 255]

The original problem is probably related with the fact that if you have width of 100 and you iterate over horizontal pixels, you'll only get values 0 to 99. So, dividing 99 by 100 is never 1. What you need is something like 255*(column+1)/width


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

iRow is between 0 and (iHeight-1), so if we want a value between 0 and 1 we need to divide by (iHeight-1). We actually want a value between 0 and 255, so we just scale up by 255. Finally we want to start at the maximum and descend to the minimum, so we just subtract the value from 255.

At the endpoints:

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

Note that iHeight must be greater than or equal to 2 for this to work (you'll get a divide by zero if it is 1).

Edit: This will cause only the last row to have an alpha value of 0. You can get a more even distribution of alpha values with

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

however, if iHeight is less than 256 the last row won't have an alpha value of 0.


Try using one of the the following calculations (they give the same result):

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

This will only work if using signed division (you use the type INT which seems to be the same as int, so it should work).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号