使用C#WinForms的透明图像

Fio*_*ona 22 .net c# transparency image picturebox

我正在使用VS 2008中的Windows窗体应用程序,我希望在另一个上面显示一个图像,顶部图像是gif或具有透明部分的东西.

基本上我有一个大图像,我想在它上面放一个小图像,这样它们就像是一个图像给用户.

我一直在尝试使用一个图片盒,但这似乎没有用,有什么建议吗?

Leo*_*son 25

几天前,我处于类似情况.您可以创建透明控件来托管图像.

using System;
using System.Windows.Forms;
using System.Drawing;

public class TransparentControl : Control
{
    private readonly Timer refresher;
    private Image _image;

    public TransparentControl()
    {
        SetStyle(ControlStyles.SupportsTransparentBackColor, true);
        BackColor = Color.Transparent;
        refresher = new Timer();
        refresher.Tick += TimerOnTick;
        refresher.Interval = 50;
        refresher.Enabled = true;
        refresher.Start();
    }

    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams cp = base.CreateParams;
            cp.ExStyle |= 0x20;
            return cp;
        }
    }

    protected override void OnMove(EventArgs e)
    {
        RecreateHandle();
    }


    protected override void OnPaint(PaintEventArgs e)
    {
        if (_image != null)
        {
            e.Graphics.DrawImage(_image, (Width / 2) - (_image.Width / 2), (Height / 2) - (_image.Height / 2));
        }
    }

    protected override void OnPaintBackground(PaintEventArgs e)
    {
       //Do not paint background
    }

    //Hack
    public void Redraw()
    {
        RecreateHandle();
    }

    private void TimerOnTick(object source, EventArgs e)
    {
        RecreateHandle();
        refresher.Stop();
    }

    public Image Image
    {
        get
        {
            return _image;
        }
        set
        {
            _image = value;
            RecreateHandle();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Nav*_*Nav 6

PictureBox有2层图像:BackgroundImage和Image,您可以相互独立使用,包括绘图和清除.