c# - 使用 C# WinForms 的透明图像

标签 c# .net image transparency picturebox

我正在 VS 2008 中开发一个 Windows 窗体应用程序,我想在另一个图像之上显示一个图像,顶部图像是 gif 或具有透明部分的图像。

基本上我有一张大图片,如果有的话,我想在上面放一张小图片,这样它们对用户来说就好像是一张图片。

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

最佳答案

几天前我遇到了类似的情况。您可以创建一个透明控件来托管您的图像。

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

关于c# - 使用 C# WinForms 的透明图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/395256/

相关文章:

.net - .NET 运行时何时保持 COM 对象的引用计数 > 1?

c# - Task.WhenAll 订单的结果有保证吗?

.net - Visual Studio 中的项目位置不受信任错误

php - 上传和调整图像大小时PNG黑色背景

c# - 在 Raspberry pi c# 上赢得 10 IoT TPM

c# - 如何将列表集合转换为派生集合对象?

android - ImageView 中的图像显示小于预期 (Android)

image - 在高清图像上应用 WebGL 过滤器会剪切图像(结构 V2-beta-6)

c# - 更改 tabControl 的 Tab 大小

c# - 比较两个字符串时如何不包含换行符