【发布时间】:2010-10-15 20:01:38
【问题描述】:
好的,所以我正在为使用 C# 的某个人创建一个“Windows 窗体应用程序”,我想让 UI 对他来说更有趣。
主窗体看起来像一个大表盘,上面排列着自定义按钮。 (我说的是自定义按钮,因为它们实际上是我创建的简单用户控件,有一个 PictureBox 和一个 Label,当用户指向它时会放大,然后在鼠标光标移到外面。还有一个 Image 属性,它设置 PictureBox 的 Image 并用作所谓的自定义按钮的图标。)
我使用了两个名为 tmrEnlarge 和 tmrShrink 的计时器,它们分别在 MouseEnter 和 MouseLeave 事件上激活。基本上只有几个简单的函数来增加和减少在我的自定义控件中使用的 PictureBox 的大小,并使它看起来像是在放大......
它工作得很好,但问题是,当鼠标同时悬停多个控件时,动画会减慢 dows(在我看来这是正常的,因为计时器不是做我所做的事情的最佳方式!) 我也尝试过使用线程,但问题仍然存在! :-(
我想知道做这种事情的最佳方法是什么?
编辑:
这是我用于直接在控件上绘制图像而不使用 PictureBox 的代码:
(这只是一个快速版本,它在绘制图像后留下残留物,这对我来说现在并不重要)
public partial class DDAnimatingLabel : UserControl
{
public Image Image { get; set; }
public DDAnimatingLabel()
{
InitializeComponent();
}
private void DDAnimatingLabel_MouseEnter(object sender, EventArgs e)
{
tmrEnlarge.Enabled = true;
}
protected override void OnPaint(PaintEventArgs e)
{
if (Image != null)
{
e.Graphics.DrawImage(this.Image, e.ClipRectangle);
}
else
base.OnPaint(e);
}
private void tmrEnlarge_Tick(object sender, EventArgs e)
{
if (Size.Width >= MaximumSize.Width)
{
tmrEnlarge.Enabled = false;
return;
}
Size s = Size;
s.Height += 4;
s.Width += 4;
Size = s;
Point p = Location;
p.X -= 2;
p.Y -= 2;
Location = p;
}
private void tmrShrink_Tick(object sender, EventArgs e)
{
if (tmrEnlarge.Enabled)
return;
if (Size.Width == MinimumSize.Width)
{
tmrShrink.Enabled = false;
return;
}
Size s = Size;
s.Height -= 4;
s.Width -= 4;
Size = s;
Point p = Location;
p.X += 2;
p.Y += 2;
Location = p;
}
private void DDAnimatingLabel_MouseLeave(object sender, EventArgs e)
{
tmrShrink.Enabled = true;
}
}
【问题讨论】:
-
你的开场白是矛盾的:WinForms +“更有趣一点”。正确的解决方案是为 WPF 转储 WinForms。 WPF 是为这种确切的场景而设计的。你能在 WinForms 中完成它吗?当然,您将继续遇到此类问题。如果您坚持,我建议您完全摆脱这些控件,而只是模拟它们。
-
我想使用 WPF,但由于我不太擅长它,所以我只使用了传统的 WinForms。 “模仿”它到底是什么意思?
-
画图不需要画框,画出来就行(OnPaint -> e.Graphics.DrawImage)。你不需要一个标签来绘制文本(e.Graphics.DrawText)。要处理输入(鼠标和键盘),您只需在表单上执行此操作,点击测试以找出单击了哪个元素或键盘的焦点标志),然后响应。
-
啊哈!谢谢你的提示!我想知道这真的会提高性能吗?
-
按你说的试过了,还是性能不好!当我使用这种类型的多个控件时会出现一些滞后。
标签: user-controls