【发布时间】:2010-12-16 08:22:20
【问题描述】:
我正在尝试在 WPF 中创建一个闪亮的加载微调器。它应该有一个圆圈,它应该旋转,在我处理一些数据时给用户一些可以看的东西。附图片。您可能会注意到实际结果的质量有些低。那是因为无论我尝试做什么,微调器都会占用大约 5% 到 7% 的 CPU。这对我来说是不可接受的,因为......好吧,它是一个微调器。当计算机忙于做某事时它会旋转,坦率地说,我希望它早日做某事。
(来源:bayimg.com)
好的,所以 XAML 代码定义了两个嵌套网格,如下所示:
<Grid
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="WPFTest.Spinner"
Name="View" Width="40" Height="40">
<Grid Name="Grid" Width="40" Height="40" >
<Grid.CacheMode>
<BitmapCache EnableClearType="False" RenderAtScale="1" SnapsToDevicePixels="False"/>
</Grid.CacheMode>
</Grid>
</Grid>
其余的在代码隐藏中,基本上是添加几个省略号并设置动画。
首先我创建椭圆的方法:
private static Ellipse GetEllipse(double x, double y, double opacity)
{
return new Ellipse
{
Fill = new SolidColorBrush(Colors.White),
Width = Size,
Height = Size,
Margin = new Thickness(x, y, 0, 0),
Opacity = opacity
};
}
微调器构造函数
public Spinner()
{
InitializeComponent();
const double step = 2 * Math.PI / Count; //Cound is const = 8
const double r = 1.4 * Field; //Field is const = 40
double angle = 0;
for (var i = 0; i < Count; i++)
{
Grid.Children.Add(GetEllipse(r * Math.Cos(angle), r * Math.Sin(angle), 1 - i/(double) Count));
angle += step;
}
_doubleAnimation = new DoubleAnimation(0, 360, new Duration(new TimeSpan(0, 0, 1)))
{
RepeatBehavior = RepeatBehavior.Forever,
};
Grid.RenderTransform = new RotateTransform(0, Field, Field);
RenderOptions.SetBitmapScalingMode(this, BitmapScalingMode.NearestNeighbor); //Low quality!
Grid.RenderTransform.BeginAnimation(RotateTransform.AngleProperty, _doubleAnimation );
}
现在这一切基本上都可以工作了,当您删除将所有内容设置为低质量的行时,它甚至有点漂亮。但它最终没有用。如果我正在加载一些东西并且这个微调器占用了我 5-7% 的 CPU,那么这对我来说就是个问题。当然,多核……随便。不,这应该有效! :)
我的下一个解决此问题的最佳方法是不要旋转微调器,只需在一段时间后重置每个椭圆的颜色。我最终会尝试这样做,但同时知道发生了什么以及为什么如此简单的动画会永远持续下去会很有趣。此外,如果我没有设置“MakeAnimationWorkBetter”属性,我将非常有义务找出在哪里以及如何...
提前致谢。
【问题讨论】:
标签: c# wpf performance animation