代码之家  ›  专栏  ›  技术社区  ›  Kepboy

如何绘制不透明度为50%的位图?

  •  0
  • Kepboy  · 技术社区  · 17 年前

    我有一个带有alpha通道的.png文件,在面板控件上用作背景图像。在某些情况下,控制被禁用。当它被禁用时,我希望背景图像是50%透明的,这样用户就可以获得一些关于控件状态的视觉指示。

    有人知道如何使位图图像50%透明吗?

    在这个阶段,我唯一可能的解决方案是将位图图像绘制成一个新的位图,然后使用面板的背景色绘制它的顶部。虽然这是可行的,但它不是我首选的解决方案,因此这个问题。

    3 回复  |  直到 17 年前
        1
  •  1
  •   Kris Erickson    17 年前

    下面是一些代码,用于向图像添加alpha通道。如果需要50%的alpha,可以将128设置为alpha参数。注意:这将创建位图的副本…

        public static Bitmap AddAlpha(Bitmap currentImage, byte alpha)
        {
            Bitmap alphaImage;
            if (currentImage.PixelFormat != PixelFormat.Format32bppArgb)
            {
                alphaImage = new Bitmap(currentImage.Width, currentImage.Height, PixelFormat.Format32bppArgb);
                using (Graphics gr = Graphics.FromImage(tmpImage))
                {
                    gr.DrawImage(currentImage, 0, 0, currentImage.Width, currentImage.Height);
                }
            }
            else
            {
                alphaImage = new Bitmap(currentImage);
            }
    
            BitmapData bmData = alphaImage.LockBits(new Rectangle(0, 0, alphaImage.Width, alphaImage.Height),
                ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
    
            const int bytesPerPixel = 4;
            const int alphaPixel = 3;
            int stride = bmData.Stride;
    
            unsafe
            {
                byte* pixel = (byte*)(void*)bmData.Scan0;
    
    
                for (int y = 0; y < currentImage.Height; y++)
                {
                    int yPos = y * stride;
                    for (int x = 0; x < currentImage.Width; x++)
                    {
                        int pos = yPos + (x * bytesPerPixel); 
                        pixel[pos + alphaPixel] = alphaByte;
                    }
                }
            }
    
            alphaImage.UnlockBits(bmData);
    
            return alphaImage;
        }
    
        2
  •  1
  •   leppie    17 年前

    你不能把它换成另一张有50%透明度的图像?

        3
  •  0
  •   Community Mohan Dere    9 年前

    可以使用.lockbits获取指向图像像素值的指针,然后更改每个像素的alpa值。请参阅此问题: Gdiplus mask image from another image

    推荐文章