安置win2d的要领请使用 Nuget 下载的要领,参见:win10 uwp win2d
下面先让大家看一下效果图再报告大家如何做
创建界面界面只需要很简单两句代码,第一句代码是定名引用,第二句代码就是添加 win2d
xmlns:canvas="using:Microsoft.Graphics.Canvas.UI.Xaml" <canvas:CanvasAnimatedControl x:Name="canvas" ClearColor="Black" Update="Canvas_OnUpdate" Draw="Canvas_Draw"></canvas:CanvasAnimatedControl>这里为何使用 CanvasAnimatedControl 而不是使用 CanvasControl ?因为需要进行更新,CanvasAnimatedControl供给了一些事件,这些事件可以用来做动画。
后台的要领在Canvas_OnUpdate就写更新所有萤火虫的代码,在Canvas_Draw就写画出萤火虫的代码。
萤火虫于是开始创建萤火虫的代码,在创建之前,需要一个随机的类,这个类用于控制萤火虫的呼吸和移动,都是随机的。
在指定的范畴之内,随机取一个点,这个点作为目的的点。于是当前的值就开始移动向目的的点,移动的过程存在速度。
从这里可以知道,这个类需要下面这些属性
public double Value { get; set; } public double To { get; set; } public double Dalue { get; set; } public double Ma { get; set; } public double Mi { get; set; } /// <summary> /// 加速度 /// </summary> public double Po { get; set; }此中 Dalue 就是速度,从 Value 到 To 的速度,这个速度在随时可以被改削。
下面是这个类全部代码
class Ran { public Ran(double value, double ma, double mi) { Value = value; Ma = ma; Mi = mi; To = ran.NextDouble() * (Ma - Mi) + Mi; } public double Value { get; set; } public double To { get; set; } public double Dalue { get; set; } public double Ma { get; set; } public double Mi { get; set; } public bool EasingFunction { get; set; } /// <summary> /// 加速度 /// </summary> public double Po { get; set; } public void Time(TimeSpan time) { if (Math.Abs(Dalue) < 0.000001) { if (Math.Abs(Po) < 0.0001) { Dalue = Math.Abs(Value - To) / ran.Next(10, 300); } else { Dalue = Po; } } //减数 if (EasingFunction && Math.Abs(Value - To) < Dalue*10/*如果接近*/) { Dalue /= 2; if (Math.Abs(Dalue) < 1) { Dalue = 1; } } int n = 1; if (Value > To) { n = n * -1; } Value += n * Dalue * time.TotalSeconds * 2; if (n > 0 && Value >= To) { Value = To; To = ran.NextDouble() * (Ma - Mi) + Mi; Dalue = 0; } if (n < 0 && Value <= To) { Value = To; To = ran.NextDouble() * (Ma - Mi) + Mi; Dalue = 0; } } private static Random ran = new Random(); }下面就是主要的类FireflyParticle包罗了位置和颜色,差别透明度,固然不透明度可以做呼吸效果,于是这些值都需要做随机移动
class FireflyParticle { public FireflyParticle(Rect bound) { Point = new Point(ran.Next((int) bound.Width), ran.Next((int) bound.Height)); _x = new Ran(Point.X, bound.Width, 0) { EasingFunction = true, }; _y = new Ran(Point.Y, bound.Height, 0) { EasingFunction = true, }; _radius = new Ran(ran.Next(2, 5), 5, 2) { Po = 0.71 }; Bound = bound; } public FireflyParticle() { } public void Time(TimeSpan time) { _radius.Time(time); _opColor.Time(time); _x.Time(time); _y.Time(time); Radius = _radius.Value; OpColor = _opColor.Value; Point = new Point(_x.Value, _y.Value); } public Point Point { get; set; } public Rect Bound { get { return _bound; } set { _bound = value; _x.Ma = value.Width; _y.Ma = value.Height; } } public double Radius { get; set; } = 10; public Color CenterColor { get; set; } = Color.FromArgb(255, 252, 203, 89); public double OpColor { set; get; } = 1; private static Random ran = new Random(); private Ran _radius; private Ran _opColor = new Ran(1, 1, 0.001); private Ran _x; private Ran _y; private Rect _bound; }