本文实例为大家分享了WPF实现背景灯光随鼠标闪动的具体代码,供大家参考,具体内容如下
实现效果如下:
思路:将容器分割成组合三角形Path,鼠标移动时更新每个三角形的填充颜色。
步骤:
1、窗体xaml
只需放置一个Canvas。
2、交互逻辑
////// MainWindow.xaml 的交互逻辑 /// public partial class MainWindow : Window { private Point lastMousePosition = new Point(0, 0);//鼠标位置 private int triangleLength = 100;//三角形边长 public MainWindow() { InitializeComponent(); this.Loaded += MainWindow_Loaded; CompositionTarget.Rendering += UpdateTriangle; this.container.PreviewMouseMove += UpdateLastMousePosition; } private void MainWindow_Loaded(object sender, RoutedEventArgs e) { //将长方形容易划分成组合三角形 int horizOntalCount= (int)(this.container.ActualWidth / triangleLength); int verticalCount = (int)(this.container.ActualHeight / triangleLength); for (int i = 0; ichildList = GetChildObjects (this.container); for (int i = 0; i /// 获得所有子控件 /// private List GetChildObjects (System.Windows.DependencyObject obj) where T : System.Windows.FrameworkElement { System.Windows.DependencyObject child = null; List childList = new List (); for (int i = 0; i (child)); } return childList; } /// /// 截取两个指定字符中间的字符串 /// public static string MidStrEx(string sourse, string startstr, string endstr) { string result = string.Empty; int startindex, endindex; try { startindex = sourse.IndexOf(startstr); if (startindex == -1) return result; string tmpstr = sourse.Substring(startindex + startstr.Length); endindex = tmpstr.IndexOf(endstr); if (endindex == -1) return result; result = tmpstr.Remove(endindex); } catch (Exception ex) { } return result; } }
说明:当组合三角形过多时,会有明显卡顿,需要优化色彩更新方法。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。