我正在構建一個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