在WinForms上绘制透明图像

本文关键字:透明图 图像 透明 绘制 WinForms | 更新日期: 2023-09-27 18:19:44

我需要在WinForms上绘制透明的PNG图像。我有一个基类:

public abstract class BaseSkinable : Panel
    {
        protected BaseSkinable()
        {
            this.SetStyle(ControlStyles.DoubleBuffer, true);
            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            this.SetStyle(ControlStyles.UserPaint, true);
            this.SetStyle(ControlStyles.ResizeRedraw, true);
        }
    protected abstract void OnDraw(Graphics graphics);

    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams cp = base.CreateParams;
            cp.ExStyle |= 0x00000020;
            return cp;
        }
    }
    protected override void OnPaintBackground(PaintEventArgs e) { }
    protected override void OnPaint(PaintEventArgs e)
    {
        e.Graphics.TextRenderingHint =
            System.Drawing.Text.TextRenderingHint.AntiAlias;
        e.Graphics.InterpolationMode =
            System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        e.Graphics.PixelOffsetMode =
            System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
        e.Graphics.SmoothingMode =
            System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        OnDraw(e.Graphics);
    }
}

在继承类中:

    protected override void OnDraw(Graphics graphics)
    {
        Image toDraw = SelectImageToDraw();
        if (toDraw == null)
        {
            NoImageDraw(graphics);
            return;
        }
        int width = toDraw.Size.Width;
        int height = toDraw.Size.Height;
        Rectangle rect = new Rectangle(0, 0, width, height);
        graphics.DrawImage(toDraw, rect); 
    }

若用户将鼠标移到控件上,我需要重新绘制图像。但问题是反对绘制覆盖旧图像。就像我们画图层一样。Winforms可能不清楚图形和我的方法绘制旧图片。如何解决它,可能我做错了什么。

在WinForms上绘制透明图像

很难理解你的问题是什么——但你想在画东西之前先清除背景吗?

使用Graphics对象,可以使用背景色调用Clear off。如果它后面有另一个图像,我可以看到你的一些沮丧——但我认为你只需要设置一个透明的颜色(并为Clear方法提供透明的颜色)。在我看来,这应该会把一切都清理干净。

http://msdn.microsoft.com/en-us/library/system.drawing.graphics.clear%28v=vs.110%29.aspx

希望这能帮助或回答你想要回答的问题。