我正在构建一个Control
派生类,它支持Opcacity
属性。
这种控制可以同时承载的文字和图片,并会比布尔淡化出来,并在
这里是我的代码:C#中的淡入淡出控制#
internal class FadeControl : Control
{
private int opacity = 100;
public FadeControl()
{
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
}
public int Opacity
{
get
{
return opacity;
}
set
{
if (value > 100) opacity = 100;
else if (value < 1) opacity = 1;
else opacity = value;
if (Parent != null)
Parent.Invalidate(Bounds, true);
}
}
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle = cp.ExStyle | 0x20;
return cp;
}
}
protected override void OnPaintBackground(PaintEventArgs e)
{
//do nothing
}
protected override void OnMove(EventArgs e)
{
RecreateHandle();
}
protected override void OnPaint(PaintEventArgs e)
{
using (Graphics g = e.Graphics)
{
Rectangle bounds = new Rectangle(0, 0, Width - 1, Height - 1);
int alpha = (opacity * 255)/100;
using (Brush bckColor = new SolidBrush(Color.FromArgb(alpha, BackColor)))
{
if (BackColor != Color.Transparent)
g.FillRectangle(bckColor, bounds);
}
ColorMatrix colorMatrix = new ColorMatrix();
colorMatrix.Matrix33 = (float)alpha/255;
ImageAttributes imageAttr = new ImageAttributes();
imageAttr.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
if (BackgroundImage != null)
g.DrawImage(BackgroundImage, bounds, 0, 0, Width, Height, GraphicsUnit.Pixel, imageAttr);
if (Text != string.Empty)
{
using (Brush txtBrush = new SolidBrush(Color.FromArgb(alpha, ForeColor)))
{
g.DrawString(Text, Font, txtBrush, 5, 5);
}
}
}
}
protected override void OnBackColorChanged(EventArgs e)
{
if (Parent != null)
Parent.Invalidate(Bounds, true);
base.OnBackColorChanged(e);
}
protected override void OnParentBackColorChanged(EventArgs e)
{
Invalidate();
base.OnParentBackColorChanged(e);
}
}
我的推杆其中有一个计时器上有一个窗体上的控件。
定时器将控件的不透明度从0设置为100,并返回并且工作正常。
我试图解决的问题是,控制闪烁,同时改变其不透明度。
将控件设置为ControlStyles.DoubleBuffer
将使窗体上的控件不可见。
任何建议将受到欢迎。
当您使用WS_EX_TRANSPARENT时,这是不可避免的。所以不要使用它。 – 2013-03-19 14:08:28
[淡入一个面板 - Windows窗体]的可能重复(http://stackoverflow.com/questions/10178559/fade-a-panel-windows-forms) – 2013-03-19 14:08:36
链接上的控件不支持透明背景色。我希望cotrol能够在包含PNG图像和文本的情况下淡入淡出。 – toy4fun 2013-03-19 14:48:16