【问题标题】:Clear background of transparent user control透明用户控件的清晰背景
【发布时间】:2011-12-09 23:37:23
【问题描述】:

我正在研究 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# 但它很慢并且使控件闪烁。

你有什么想法如何清除这个背景并保持控制的透明度?

【问题讨论】:

  • 您需要什么样的透明度?只是要显示的父背景?或者您想要其他控件和/或其他窗口的透明度?

标签: c# user-controls background transparent


【解决方案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。它在设计时不起作用。

【讨论】:

  • 我注意到另一个问题。当按钮处于清晰形式(例如在 PictureBox 上)时,位图包含绘制的他并且无法正常工作。如何先重绘背景然后我的控件(没有我的控件有位图)?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 2013-12-07
  • 2014-06-19
  • 2014-05-06
相关资源
最近更新 更多