透明图像用C#的WinForms图像、透明、WinForms

2023-09-02 21:08:08 作者:曾经少年薄荷凉

我工作的Windows窗体应用程序在VS 2008中,我要在另一个顶部显示一个图像,与顶尖的图像是一个GIF或东西透明部分。

I am working on a Windows Forms application in VS 2008, and I want to display one image over the top of another, with the top image being a gif or something with transparent parts.

基本上我有一个大的形象,我想提出一个小图像的顶部,如果它,让他们还挺显示为一个图像给用户。

Basically I have a big image and I want to put a little image on top if it, so that they kinda appear as one image to the user.

我一直在试图用一个图片,但是这似乎并没有工作过,有什么建​​议?

I've been trying to use a picturebox, but this doesn't seem to have worked, any suggestions?

推荐答案

我是在一个类似的情况前几天。您可以创建一个透明的控制来承载你的形象。

I was in a similar situation a couple of days ago. You can create a transparent control to host your image.

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();
        }
    }
}