前面写了个简单的实现( http://blog.csdn.net/yysyangyangyangshan/article/details/9280439),不过效果不太好,各个点之间没有连接起来。这里增加连接各个按键。
其他代码不变,只改动PatternPasswordKeyboard类。
/// <summary> /// PatternPasswordKeyboard.xaml 的交互逻辑 /// </summary> public partial class PatternPasswordKeyboard : UserControl { public string password = string.Empty;//最终密码 private bool isMouseDonw = false;//控制只有鼠标按下的滑动才有效 private List<KeyButton> keyButtons = new List<KeyButton>();//密码所在的控件 private List<Point> points = new List<Point>(); public PatternPasswordKeyboard() { InitializeComponent(); this.MouseUp += new MouseButtonEventHandler(MainWindow_MouseUp); this.MouseDown += new MouseButtonEventHandler(MainWindow_MouseDown); } /// <summary> /// 重置 /// </summary> 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); } }
效果图:
代码下载:
http://download.csdn.net/detail/yysyangyangyangshan/5727105