设置 Format32bppArgb 的 Alpha 值
我一直在尝试为格式为 Format32bppArgb 的位图手动设置 alpha 值。在此代码示例中,我将它们全部设置为 0.5f,但是,将来它们将是不同的值,而不是全部 0.5f/128(因为这是我的测试用例,只是为了使其正常工作)。如何快速正确设置位图的 Alpha 值?我可以使用 SetPixel(),但是,与仅锁定/解锁位图相比,SetPixel() 对于大图像来说速度慢得可怕。
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
System.Drawing.Imaging.BitmapData bmpData =
bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
bmp.PixelFormat);
// Get the address of the first line.
IntPtr ptr = bmpData.Scan0;
// Declare an array to hold the bytes of the bitmap.
int bytes = Math.Abs(bmpData.Stride) * bmp.Height;
byte[] rgbValues = new byte[bytes];
// Copy the RGB values into the array.
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
for (int counter = 0; counter < rgbValues.Length; counter += 4)
{
rgbValues[counter] = 255;
rgbValues[counter + 1] = 255;
rgbValues[counter + 2] = 255;
rgbValues[counter + 3] = 128;
}
// Copy the RGB values back to the bitmap
System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);
// Unlock the bits.
bmp.UnlockBits(bmpData);
I have been trying to set the alpha values manually for a Bitmap with the format of Format32bppArgb . In this code example, I am setting them all to 0.5f, however, they will be different values in the future and not all 0.5f/128 (as this is my test case to just get this working). How can I properly set the alpha values for a bitmap quickly? I could use SetPixel(), however, SetPixel() is horrifically slow for large images compared to just locking/unlocking the bitmap.
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
System.Drawing.Imaging.BitmapData bmpData =
bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
bmp.PixelFormat);
// Get the address of the first line.
IntPtr ptr = bmpData.Scan0;
// Declare an array to hold the bytes of the bitmap.
int bytes = Math.Abs(bmpData.Stride) * bmp.Height;
byte[] rgbValues = new byte[bytes];
// Copy the RGB values into the array.
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
for (int counter = 0; counter < rgbValues.Length; counter += 4)
{
rgbValues[counter] = 255;
rgbValues[counter + 1] = 255;
rgbValues[counter + 2] = 255;
rgbValues[counter + 3] = 128;
}
// Copy the RGB values back to the bitmap
System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);
// Unlock the bits.
bmp.UnlockBits(bmpData);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您希望在整个位图上具有相同的 alpha 值,最好的方法是使用 ColorMatrix。查看 Microsoft 提供的此示例:
http://msdn .microsoft.com/en-us/library/w177ax15(v=vs.71).aspx
The best way to do this, providing you want to have the same alpha value on your entire bitmap, is to use a ColorMatrix. Check out this example by Microsoft:
http://msdn.microsoft.com/en-us/library/w177ax15(v=vs.71).aspx