我的问题是我想在按钮上放置一个带有 png 的图片框,但 WinForms 似乎不支持那里的透明度。1. 是的,我试过 Parent 2. 是的,我试过 Color.Transparent
我最后一次尝试也没有工作,我对此一无所知。也许你可以帮助我。然而,这是我迄今为止最接近的尝试。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
namespace Parameter2
{
public class TransPicturebox : Control
{
public TransPicturebox()
{
this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.UserPaint, true);
this.BackColor = Color.Transparent;
}
private Image _Image;
public Image Image
{
get
{
return _Image;
}
set
{
_Image = value;
}
}
private bool _autoscale = true;
public bool AutoScale
{
get
{
return _autoscale;
}
set
{
_autoscale = value;
}
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (_Image != null) //keep from crashing if there is no image
{
if (_autoscale)
{
//Auto Scale the image to fit in the text box
Rectangle rectangle = new Rectangle();
Size size = this.Image.Size;
float num = Math.Min((float)(((float)base.ClientRectangle.Width) / ((float)size.Width)), (float)(((float)base.ClientRectangle.Height) / ((float)size.Height)));
rectangle.Width = (int)(size.Width * num);
rectangle.Height = (int)(size.Height * num);
rectangle.X = (base.ClientRectangle.Width - rectangle.Width) / 2;
rectangle.Y = (base.ClientRectangle.Height - rectangle.Height) / 2;
e.Graphics.DrawImage(_Image, rectangle);
}
else
{
e.Graphics.DrawImage(_Image, new Point(0, 0));
}
}
}
}
}