【WPF】如何使用wpf实现屏幕最前端的绘图?
引言
在知乎上面看到如何使用wpf实现屏幕最前端的绘图? 这么一个问题,觉得全屏弹幕很有趣,所以把它实现了.
实现
界面设置很简单,Window界面无边框+最大化+允许不规则+背景色透明+置顶,如下
<Window x:Class="FullScreen.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" WindowState="Maximized" Topmost="True" AllowsTransparency="True" Background="Transparent" WindowStyle="None" > <Canvas Name="canvas"> </Canvas> </Window>
弹幕信息出现的位置和速度都随机产生,还要保证永远最大化和置顶,如下
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.Loaded += MainWindow_Loaded; this.Deactivated += MainWindow_Deactivated; this.StateChanged += MainWindow_StateChanged; } /// <summary> /// 确保永远最大化 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void MainWindow_StateChanged(object sender, EventArgs e) { this.WindowState = WindowState.Maximized; } /// <summary> /// 确保永远置顶 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void MainWindow_Deactivated(object sender, EventArgs e) { this.Topmost = true; } void MainWindow_Loaded(object sender, RoutedEventArgs e) { List<string> list = new List<string>(); list.Add("你们的"); list.Add("生活"); list.Add("真丰富"); list.Add("不像我"); list.Add("一个"); list.Add("帅"); list.Add("字"); list.Add("竟贯穿了"); list.Add("一生"); Barrage(list); } /// <summary> /// 在Window界面上显示弹幕信息,速度和位置随机产生 /// </summary> /// <param name="contentlist"></param> public void Barrage(IEnumerable<string> contentlist) { Random random = new Random(); foreach (var item in contentlist) { //获取位置随机数 double randomtop = random.NextDouble(); double inittop = canvas.ActualHeight * randomtop; //获取速度随机数 double randomspeed = random.NextDouble(); double initspeed = 50 * randomspeed; //实例化TextBlock和设置基本属性,并添加到Canvas中 TextBlock textblock = new TextBlock(); textblock.Text = item; textblock.FontSize = 50; Canvas.SetTop(textblock, inittop); canvas.Children.Add(textblock); //实例化动画 DoubleAnimation animation = new DoubleAnimation(); Timeline.SetDesiredFrameRate(animation,60); //如果有性能问题,这里可以设置帧数 animation.From = 0; animation.To = canvas.ActualWidth; animation.Duration = TimeSpan.FromSeconds(initspeed); animation.AutoReverse = true; animation.RepeatBehavior = RepeatBehavior.Forever; animation.Completed += (object sender, EventArgs e) => { canvas.Children.Remove(textblock); }; //启动动画 textblock.BeginAnimation(Canvas.LeftProperty, animation); } } }
效果图
小结
本文主要利用了WPF的动画和窗体的不规则化属性,这些WPF特性使实现起来的界面效果可以千变万化.