沒想到粉絲對介面效果這麼喜歡,接下來就儘量多來點特效,當然,特效也算是動畫的一部分了。WPF裡面已經包含了很多動畫特效的功能支援了,但是,還是得自己實現,我這邊就來個自繪實現的。
彈動小球是一個很常見的頁面特效,類似於,拖動物體或者表單,實現了抖動效果一樣。還是值得學習一二的,實際上,也很簡單,只需要一個彈動係數和摩擦係數即可。
新建一個WPF專案,然後,Nuget包即可
要新增Nuget包
Install-Package SkiaSharp.Views.WPF -Version 2.88.0
其中核心邏輯是這部分,會以我設定的60FPS來重新整理當前的畫板。
skContainer.PaintSurface += SkContainer_PaintSurface;
_ = Task.Run(() =>
{
while (true)
{
try
{
Dispatcher.Invoke(() =>
{
skContainer.InvalidateVisual();
});
_ = SpinWait.SpinUntil(() => false, 1000 / 60);//每秒60幀
}
catch
{
break;
}
}
});
public class Ball
{
public double X { get; set; }
public double Y { get; set; }
public double VX { get; set; }
public double VY { get; set; }
public int R { get; set; }
public SKColor sKColor { get; set; } = SKColors.Blue;
}
/// <summary>
/// 彈動特效
/// </summary>
public class Shake
{
public SKPoint centerPoint;
public int Radius = 0;
/// <summary>
/// 彈動係數
/// </summary>
public double Spring = 0.02;
public double TargetX;
/// <summary>
/// 摩擦係數
/// </summary>
public double Friction = 0.95;
public Ball Ball;
public void Init(SKCanvas canvas, SKTypeface Font, int Width, int Height)
{
if (Ball == null)
{
Ball = new Ball();
Ball.X = 60;
Ball.Y = Height / 2;
Ball.R = 30;
}
}
/// <summary>
/// 渲染
/// </summary>
public void Render(SKCanvas canvas, SKTypeface Font, int Width, int Height)
{
Init(canvas, Font, Width, Height);
centerPoint = new SKPoint(Width / 2, Height / 2);
this.Radius = 30;
this.TargetX = Width / 2;
canvas.Clear(SKColors.White);
var ax = (TargetX - Ball.X) * Spring;
Ball.VX += ax;
Ball.VX *= Friction;
Ball.X += Ball.VX;
DrawCircle(canvas, Ball);
using var paint = new SKPaint
{
Color = SKColors.Blue,
IsAntialias = true,
Typeface = Font,
TextSize = 24
};
string by = $"by 藍創精英團隊";
canvas.DrawText(by, 600, 400, paint);
}
/// <summary>
/// 畫一個圓
/// </summary>
public void DrawCircle(SKCanvas canvas, Ball ball)
{
using var paint = new SKPaint
{
Color = SKColors.Blue,
Style = SKPaintStyle.Fill,
IsAntialias = true,
StrokeWidth = 2
};
canvas.DrawCircle((float)ball.X, (float)ball.Y, ball.R, paint);
}
public void ReSet()
{
Ball.X = 60;
}
}
這個特效原理是可以運用到任何物體上的,會產生很神奇的效果,後面可以再搞一些案例。
第一次實現特效,當初學FLash,就見到過很多特效的效果,現在自己用敲出來特效感覺是挺不一樣的。
https://github.com/kesshei/WPFSkiaShakeDemo.git
https://gitee.com/kesshei/WPFSkiaShakeDemo.git
一鍵三連呦!,感謝大佬的支援,您的支援就是我的動力!
藍創精英團隊(公眾號同名,CSDN同名,CNBlogs同名)