关于两个PictureBox重叠后透明的问题

我的系统之前就有这么个问题,当两个图片重叠的时候,上面的图片总是将下面的图片覆盖,之前因为忙一直没有腾出时间处理一下

 

 

今天实在看不下去了,然后本来想自己重新写一个,但是问了技术群的大佬,给重写了一个PictureBoxDE 类,效果如下

 

 

 完美的解决了图片的透明,下面我将把这个重写的类发出来,供大家使用参考,也顺便做一下记录

 1 public class ReiongCtr : PictureBox
 2     {
 3         protected override void OnSizeChanged(EventArgs e)
 4         {
 5             base.OnSizeChanged(e);
 6             if (BackgroundImage != null)
 7             {
 8                 Bitmap bit = (Bitmap)BackgroundImage.GetThumbnailImage(Width, Height, null, IntPtr.Zero);
 9                 Region = ImageToRegion(bit, Color.FromArgb(0, 0, 0, 0));
10             }
11         }
12         protected override void OnBackgroundImageChanged(EventArgs e)
13         {
14             base.OnBackgroundImageChanged(e);
15             if (BackgroundImage != null)
16             {
17                 Bitmap bit = (Bitmap)BackgroundImage.GetThumbnailImage(Width, Height, null, IntPtr.Zero);
18                 Region = ImageToRegion(bit, Color.FromArgb(0, 0, 0, 0));
19             }
20         }
21          
22         /// <summary>
23         /// 根据图片计算Region路径(低效率)
24         /// </summary>
25         /// <param name="img">图像资源</param>
26         /// <param name="TranColor">欲透明掉的颜色</param>
27         /// <returns>一个离散的路径信息</returns>
28         public static Region ImageToRegion(Image imgx, Color TranColor)
29         {
30             if (imgx == null) return null;
31             Region rRegion = new Region();
32             rRegion.MakeEmpty();
33 
34 
35             int ImWidth = imgx.Width;
36             int ImHeight = imgx.Height;
37             Color curColor;
38             Rectangle curRect = new Rectangle();
39             curRect.Height = 1;
40             bool isTransRgn;
41 
42             for (int y = 0; y < ImHeight; y++)
43             {
44                 isTransRgn = true;
45                 for (int x = 0; x < ImWidth; x++)
46                 {
47                     curColor = ((Bitmap)imgx).GetPixel(x, y);
48                     if (curColor == TranColor || x == ImWidth - 1)//如果遇到透明色或行尾
49                     {
50                         if (isTransRgn == false)//退出有效区
51                         {
52                             curRect.Width = x - curRect.X;
53                             rRegion.Union(curRect);
54                         }
55                     }
56                     else//非透明色
57                     {
58                         if (isTransRgn == true)//进入有效区
59                         {
60                             curRect.X = x;
61                             curRect.Y = y;
62                         }
63                     }//if curColor
64                     isTransRgn = curColor == TranColor;
65                 }
66             }
67             return rRegion;
68         }
69     }

 

posted @ 2022-04-02 17:44  PandaHuB  阅读(271)  评论(0编辑  收藏  举报