本文共 4137 字,大约阅读时间需要 13 分钟。
///效果图: 代码下载:/// PatternPasswordKeyboard.xaml 的交互逻辑 /// public partial class PatternPasswordKeyboard : UserControl { public string password = string.Empty;//最终密码 private bool isMouseDonw = false;//控制只有鼠标按下的滑动才有效 private ListkeyButtons = new List ();//密码所在的控件 private List points = new List (); public PatternPasswordKeyboard() { InitializeComponent(); this.MouseUp += new MouseButtonEventHandler(MainWindow_MouseUp); this.MouseDown += new MouseButtonEventHandler(MainWindow_MouseDown); } /// /// 重置 /// internal void PatternPasswordKeyboard_ResetPassword() { this.points.Clear(); this.password = string.Empty; foreach (KeyButton item in keyButtons) { item.SelfBacground = new SolidColorBrush(Colors.Transparent); } this.InvalidateVisual(); } void MainWindow_MouseDown(object sender, MouseButtonEventArgs e) { points.Clear(); PatternPasswordKeyboard_ResetPassword(); isMouseDonw = true; } void MainWindow_MouseUp(object sender, MouseButtonEventArgs e) { isMouseDonw = false; } private void BorderMouseMove(object sender, MouseEventArgs e) { if (!isMouseDonw) { return; } KeyButton border = sender as KeyButton; if (border == null) { return; } string key = border.Tag.ToString(); if (string.IsNullOrEmpty(key)) { return; } border.SelfBacground = new SolidColorBrush(Colors.Blue); keyButtons.Add(border); //将滑过的点保存起来 if (!password.Contains(key)) { password += key; GeneralTransform generalTransform = border.ellipseBorder.TransformToAncestor(this); Point point = generalTransform.Transform(this.TranslatePoint(new Point(0,0),this)); points.Add(point); this.InvalidateVisual(); } } protected override void OnRender(DrawingContext drawingContext) { base.OnRender(drawingContext); if (points.Count < 2) { return; } //使用画复合图形画出已经保存的点 Pen p = new Pen(new SolidColorBrush(Colors.Red), 10); GeometryGroup group = new GeometryGroup(); group.FillRule = FillRule.EvenOdd; LineGeometry myLineGeometry = null; for (int i = 0; i < points.Count;i++ ) { if (i % 2 == 0) { if (myLineGeometry != null) { myLineGeometry.EndPoint = points[i]; } myLineGeometry = new LineGeometry(); myLineGeometry.StartPoint = points[i]; } else { myLineGeometry.EndPoint = points[i]; group.Children.Add(myLineGeometry); if (i + 1 < points.Count) { myLineGeometry = new LineGeometry(); myLineGeometry.StartPoint = points[i]; group.Children.Add(myLineGeometry); } else { myLineGeometry = null; } } } SolidColorBrush mySolidColorBrush = new SolidColorBrush(); drawingContext.DrawGeometry(mySolidColorBrush, new Pen(Brushes.Green, 10), group); } }