使用CDI+製做支持半透明的Panle

建立一個自定義控件程序集,並修改父類爲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;
        }
    }
}
相關文章
相關標籤/搜索