使用CDI+制作支持半透明的Panle

C#

浏览数:144

2019-9-18

AD:资源代下载服务

创建一个自定义控件程序集,并修改父类为Panle,添加如下代码:

public partial class OpaqueLayer : Panel
{
    private Color transparentBC = Color.SkyBlue;

    [Description("设置透明背景颜色")]
    public Color TransparentBC
    {
        get
        {
            return transparentBC;
        }
        set
        {
            transparentBC = value;
            this.Invalidate();
        }
    }

    //透明度
    private int alpha = 125;

    [Description("设置透明度(0-255)")]
    public int Alpha
    {
        get  {  return alpha;  }
        set
        {
            if (value < 0)
            {
                value = 0;
            }
            else if (value > 255)
            {
                value = 255;
            }

            alpha = value;
            this.Invalidate();
        }
    }

    public OpaqueLayer()
    {
        InitializeComponent();
        //设置参数,使支持半透明、缓存、自行绘制
        SetStyle(ControlStyles.Opaque | ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint, true);
    }

    /// <summary>
    /// 自定义绘制窗体
    /// </summary>
    /// <param name="e"></param>
    protected override void OnPaint(PaintEventArgs e)
    {
        Graphics g = e.Graphics;            //获得绘图面板
        Color drawColor = Color.FromArgb(Alpha, TransparentBC);
        SolidBrush backColorBrush = new SolidBrush(drawColor);
        g.FillRectangle(backColorBrush, 0, 0, Width, Height);//绘制半透明
    }

    //该参数封装创建控件时所需的信息,必须重写该参数,以支持透明
    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams cp = base.CreateParams;
            cp.ExStyle |= 0x20;  // 开启 WS_EX_TRANSPARENT,使控件支持透明
            return cp;
        }
    }
}

 

作者:一只独行的猿