在C#.net中使重叠的图片框透明

mac*_*ers 5 c# transparent winforms

我有两个重叠的图片框.两个图片框的图像都有一些透明像素.我想通过重叠图片框的透明像素看到底部图片框.

我尝试将两个图片框的背景颜色设置为透明.但它只是将图片框的背面颜色设置为表单的背景颜色.

Han*_*ant 5

显然你正在使用Winforms.是的,通过绘制父像素来模拟透明度.哪个是表单,你只看到表单像素,堆叠效果不起作用.有一篇知识库文章显示了解决方法.这很痛苦.另一种方法是不使用PictureBox控件,而只是在窗体的Paint事件中绘制图像.

考虑WPF,它有一个非常不同的渲染模型,可以轻松支持透明度.


Mor*_*aos 5

该问题的解决方案可能多种多样,这主要取决于您的技能,工作量取决于您处理的图像类型。例如,如果图像始终具有相同的分辨率、大小和重叠图像支持透明度,您可以尝试对两个Image对象进行操作并将一个对象绘制在另一个对象上,然后以PictureBox. 或者,如果您需要在应用程序的不同位置多次执行此操作,您甚至可以考虑创建自己的UserContriol.

回答这个问题的代码,ResizeImage特别是方法,展示了如何创建调整大小的高质量图像,你只需要稍微改变它。使其获得两个Images作为输入参数,并将其更改为在另一个图像上绘制一个图像。

更改可能如下所示

    public static Bitmap CombineAndResizeTwoImages(Image image1, Image image2, int width, int height)
    {
        //a holder for the result
        Bitmap result = new Bitmap(width, height);

        //use a graphics object to draw the resized image into the bitmap
        using (Graphics graphics = Graphics.FromImage(result))
        {
            //set the resize quality modes to high quality
            graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //draw the images into the target bitmap
            graphics.DrawImage(image1, 0, 0, result.Width, result.Height);
            graphics.DrawImage(image2, 0, 0, result.Width, result.Height);
        }

        //return the resulting bitmap
        return result;
    }
Run Code Online (Sandbox Code Playgroud)

并使用它,例如,像这样:

  pictureBox1.Image = CombineAndResizeTwoImages(Image.FromFile("c:\\a.png"), Image.FromFile("c:\\b.png"), 100,100);
Run Code Online (Sandbox Code Playgroud)

但这是唯一的示例,您必须根据自己的需要对其进行调整。祝你好运。