我一直在尝试为格式为32bppargb的位图手动设置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);

最佳答案

如果希望在整个位图上具有相同的alpha值,最好的方法是使用colormatrix。请查看Microsoft提供的以下示例:
http://msdn.microsoft.com/en-us/library/w177ax15(v=vs.71).aspx

10-06 05:51