我正在使用ImageButton,在其中我绘制了此按钮的每个状态(我有每个状态的几个图像)(如mouseOver,mouseDown等)。
我使用此代码使控件透明:
public ImageButton()
{
InitializeComponent();
this.SetStyle(ControlStyles.Opaque, true);
this.SetStyle(ControlStyles.OptimizedDoubleBuffer, false);
}
protected override CreateParams CreateParams
{
get
{
CreateParams parms = base.CreateParams;
parms.ExStyle |= 0x20;
return parms;
}
}
但是有一个问题,在几次状态切换后,角落变得尖锐和丑陋,为了解决这个问题我需要清除背景,但如果我的控制是透明的那么这是不可能的。
我尝试过这个解决方案:Clearing the graphics of a transparent panel C# 但它很慢并且使控制闪烁。
您对如何清除此背景并保持控制透明度有任何想法吗?
答案 0 :(得分:1)
好的,我已经解决了这个问题。 我通过将控件设置为不透明来解决它,我绘制了受我控制的画布,作为我的ImageButton的背景。
解决方案(在Paint事件中):
//gets position of button and transforms it to point on whole screen
//(because in next step we'll get screenshot of whole window [with borders etc])
Point btnpos = this.Parent.PointToScreen(new Point(Location.X, Location.Y));
//now our point will be relative to the edges of form
//[including borders, which we'll have on our bitmap]
if (this.Parent is Form)
{
btnpos.X -= this.Parent.Left;
btnpos.Y -= this.Parent.Top;
}
else
{
btnpos.X = this.Left;
btnpos.Y = this.Top;
}
//gets screenshot of whole form
Bitmap b = new Bitmap(this.Parent.Width, this.Parent.Height);
this.Parent.DrawToBitmap(b, new Rectangle(new Point(0, 0), this.Parent.Size));
//draws background (which simulates transparency)
e.Graphics.DrawImage(b,
new Rectangle(new Point(0, 0), this.Size),
new Rectangle(btnpos, this.Size),
GraphicsUnit.Pixel);
//do whatever you want to draw your stuff
PS。它在设计时没有用。