【发布时间】:2015-01-14 20:30:55
【问题描述】:
我正在寻找如何在 C# WinForms 程序中绘制透明控件(能够看到其背后)。
我需要类似下图的东西。如您所见,在图像的中心有一个半透明的组件(实际上它就像一个光标),它正在填充一个圆形扇区。
我专注于获得一个半透明的控件,现在,如果我在我的组件上设置一个透明背景(从标准控件类继承),它的背景与父背景的颜色相同。显然在 WinForms 中获取透明控件很复杂,但图像是在 WinForms 程序上拍摄的。
你有什么想法吗?这可能吗?
编辑: 抱歉,如果这是一个重复的问题,我将在下面粘贴我的代码,这是其他程序员的代码,但我在您的链接中包含了建议。 (只显示与问题相关的代码,没有属性,没有属性等)
public partial class LoadingCircle : Control
{
public LoadingCircle()
{
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
SetStyle(ControlStyles.ResizeRedraw, true);
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
//Added following StackOverflow
SetStyle(ControlStyles.Opaque, true);
this.BackColor = Color.Transparent;
m_Color = DefaultColor;
GenerateColorsPallet();
GetSpokesAngles();
GetControlCenterPoint();
m_Timer = new Timer();
m_Timer.Tick += new EventHandler(aTimer_Tick);
ActiveTimer();
this.Resize += new EventHandler(LoadingCircle_Resize);
}
void aTimer_Tick(object sender, EventArgs e)
{
m_ProgressValue = ++m_ProgressValue % m_NumberOfSpoke;
Invalidate();
}
protected override void OnPaint(PaintEventArgs e)
{
if (m_NumberOfSpoke > 0)
{
e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
int intPosition = m_ProgressValue;
for (int intCounter = 0; intCounter < m_NumberOfSpoke; intCounter++)
{
intPosition = intPosition % m_NumberOfSpoke;
DrawLine(e.Graphics,
GetCoordinate(m_CenterPoint, m_InnerCircleRadius, m_Angles[intPosition]),
GetCoordinate(m_CenterPoint, m_OuterCircleRadius, m_Angles[intPosition]),
m_Colors[intCounter], m_SpokeThickness);
intPosition++;
}
}
base.OnPaint(e);
}
//Added following StackOverflow
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle |= 0x20; //WS_EX_TRANSPARENT
return cp;
}
}
protected override void OnBackColorChanged(EventArgs e)
{
if (this.Parent != null) Parent.Invalidate(this.Bounds, true);
base.OnBackColorChanged(e);
}
protected override void OnParentBackColorChanged(EventArgs e)
{
this.Invalidate();
base.OnParentBackColorChanged(e);
}
//----- End
private void DrawLine(Graphics _objGraphics, PointF _objPointOne, PointF _objPointTwo,
Color _objColor, int _intLineThickness)
{
using(Pen objPen = new Pen(new SolidBrush(_objColor), _intLineThickness))
{
objPen.StartCap = LineCap.Round;
objPen.EndCap = LineCap.Round;
_objGraphics.DrawLine(objPen, _objPointOne, _objPointTwo);
}
}
private void ActiveTimer()
{
if (m_IsTimerActive)
m_Timer.Start();
else
{
m_Timer.Stop();
m_ProgressValue = 0;
}
GenerateColorsPallet();
Invalidate();
}
}
编辑 2:我添加了结果的图像,您可以看到我的控件 (LoadingCircle) 的背景与其父级 (窗体) 相同,但按钮保持隐藏状态。
【问题讨论】:
-
你有没有在MSDN看一眼