0

0

详解如何用WPF图形解锁控件ScreenUnLock

巴扎黑

巴扎黑

发布时间:2017-08-06 10:49:45

|

1612人浏览过

|

来源于php中文网

原创

这篇文章主要为大家详细介绍了wpf图形解锁控件screenunlock的使用方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

ScreenUnLock 与智能手机上的图案解锁功能一样。通过绘制图形达到解锁或记忆图形的目的。

本人突发奇想,把手机上的图形解锁功能移植到WPF中。也应用到了公司的项目中。

在创建ScreenUnLock之前,先来分析一下图形解锁的实现思路。

1.创建九宫格原点(或更多格子),每个点定义一个坐标值

2.提供图形解锁相关扩展属性和事件,方便调用者定义。比如:点和线的颜色(Color),操作模式(Check|Remember),验证正确的颜色(RightColor), 验证失败的颜色(ErrorColor), 解锁事件 OnCheckedPoint,记忆事件 OnRememberPoint 等;

3.定义MouseMove事件监听画线行为。 画线部分也是本文的核心。在画线过程中。程序需判断,线条从哪个点开始绘制,经过了哪个点(排除已经记录的点)。是否完成了绘制等等。

4.画线完成,根据操作模式处理画线完成行为。并调用相关自定义事件

大致思路如上,下面开始一步一步编写ScreenUnLock吧

创建ScreenUnLock


public partial class ScreenUnlock : UserControl

定义相关属性

星火作家大神
星火作家大神

星火作家大神是一款面向作家的AI写作工具

下载


/// 
  /// 验证正确的颜色
  /// 
  private SolidColorBrush rightColor;

  /// 
  /// 验证失败的颜色
  /// 
  private SolidColorBrush errorColor;

  /// 
  /// 图案是否在检查中
  /// 
  private bool isChecking;

  public static readonly DependencyProperty PointArrayProperty = DependencyProperty.Register("PointArray", typeof(IList), typeof(ScreenUnlock));
  /// 
  /// 记忆的坐标点 
  /// 
  public IList PointArray
  {
   get { return GetValue(PointArrayProperty) as IList; }
   set { SetValue(PointArrayProperty, value); }
  }

  /// 
  /// 当前坐标点集合
  /// 
  private IList currentPointArray;

  /// 
  /// 当前线集合
  /// 
  private IList currentLineList;

  /// 
  /// 点集合
  /// 
  private IList ellipseList;

  /// 
  /// 当前正在绘制的线
  /// 
  private Line currentLine;

  public static readonly DependencyProperty OperationPorperty = DependencyProperty.Register("Operation", typeof(ScreenUnLockOperationType), typeof(ScreenUnlock), new FrameworkPropertyMetadata(ScreenUnLockOperationType.Remember));
  /// 
  /// 操作类型
  /// 
  public ScreenUnLockOperationType Operation
  {
   get { return (ScreenUnLockOperationType)GetValue(OperationPorperty); }
   set { SetValue(OperationPorperty, value); }
  }

  public static readonly DependencyProperty PointSizeProperty = DependencyProperty.Register("PointSize", typeof(double), typeof(ScreenUnlock), new FrameworkPropertyMetadata(15.0));
  /// 
  /// 坐标点大小 
  /// 
  public double PointSize
  {
   get { return Convert.ToDouble(GetValue(PointSizeProperty)); }
   set { SetValue(PointSizeProperty, value); }
  }


  public static readonly DependencyProperty ColorProperty = DependencyProperty.Register("Color", typeof(SolidColorBrush), typeof(ScreenUnlock), new FrameworkPropertyMetadata(new SolidColorBrush(Colors.White), new PropertyChangedCallback((s, e) =>
  {
   (s as ScreenUnlock).Refresh();
  })));

  /// 
  /// 坐标点及线条颜色
  /// 
  public SolidColorBrush Color
  {
   get { return GetValue(ColorProperty) as SolidColorBrush; }
   set { SetValue(ColorProperty, value); }
  }

     /// 
     /// 操作类型
     /// 
     public enum ScreenUnLockOperationType
     {
      Remember = 0, Check = 1
     }

初始化ScreenUnLock


public ScreenUnlock()
  {
   InitializeComponent();
   this.Loaded += ScreenUnlock_Loaded;
   this.Unloaded += ScreenUnlock_Unloaded;
   this.MouseMove += ScreenUnlock_MouseMove; //监听绘制事件
  }
 private void ScreenUnlock_Loaded(object sender, RoutedEventArgs e)
  {
   isChecking = false;
   rightColor = new SolidColorBrush(Colors.Green);
   errorColor = new SolidColorBrush(Colors.Red);
   currentPointArray = new List();
   currentLineList = new List();
   ellipseList = new List();
   CreatePoint();
  }


  private void ScreenUnlock_Unloaded(object sender, RoutedEventArgs e)
  {
   rightColor = null;
   errorColor = null;
   if (currentPointArray != null)
    this.currentPointArray.Clear();
   if (currentLineList != null)
    this.currentLineList.Clear();
   if (ellipseList != null)
    ellipseList.Clear();
   this.canvasRoot.Children.Clear();
  }

创建点


/// 
  /// 创建点
  /// 
  private void CreatePoint()
  {
   canvasRoot.Children.Clear();
   int row = 3, column = 3; //三行三列,九宫格
   double oneColumnWidth = (this.ActualWidth == 0 ? this.Width : this.ActualWidth) / 3; //单列的宽度
   double oneRowHeight = (this.ActualHeight == 0 ? this.Height : this.ActualHeight) / 3; //单列的高度
   double leftDistance = (oneColumnWidth - PointSize) / 2; //单列左边距
   double topDistance = (oneRowHeight - PointSize) / 2; //单列上边距
   for (var i = 0; i < row; i++)
   {
    for (var j = 0; j < column; j++)
    {
     Ellipse ellipse = new Ellipse()
     {
      Width = PointSize,
      Height = PointSize,
      Fill = Color,
      Tag = string.Format("{0}{1}", i, j)
     };
     Canvas.SetLeft(ellipse, j * oneColumnWidth + leftDistance);
     Canvas.SetTop(ellipse, i * oneRowHeight + topDistance);
     canvasRoot.Children.Add(ellipse);
     ellipseList.Add(ellipse);
    }
   }
  }

创建线


private Line CreateLine()
  {
   Line line = new Line()
   {
    Stroke = Color,
    StrokeThickness = 2
   };
   return line;
  }

点和线都创建都定义好了,可以开始监听绘制事件了


private void ScreenUnlock_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
  {
   if (isChecking) //如果图形正在检查中,不响应后续处理
    return;
   if (e.LeftButton == System.Windows.Input.MouseButtonState.Pressed)
   {
    var point = e.GetPosition(this);
    HitTestResult result = VisualTreeHelper.HitTest(this, point);
    Ellipse ellipse = result.VisualHit as Ellipse;
    if (ellipse != null)
    {
     if (currentLine == null)
     {
      //从头开始绘制                  
      currentLine = CreateLine();
      var ellipseCenterPoint = GetCenterPoint(ellipse);
      currentLine.X1 = currentLine.X2 = ellipseCenterPoint.X;
      currentLine.Y1 = currentLine.Y2 = ellipseCenterPoint.Y;

      currentPointArray.Add(ellipse.Tag.ToString());
      Console.WriteLine(string.Join(",", currentPointArray));
      currentLineList.Add(currentLine);
      canvasRoot.Children.Add(currentLine);
     }
     else
     {
      //遇到下一个点,排除已经经过的点
      if (currentPointArray.Contains(ellipse.Tag.ToString()))
       return;
      OnAfterByPoint(ellipse);
     }
    }
    else if (currentLine != null)
    {
     //绘制过程中
     currentLine.X2 = point.X;
     currentLine.Y2 = point.Y;

     //判断当前Line是否经过点
     ellipse = IsOnLine();
     if (ellipse != null)
      OnAfterByPoint(ellipse);
    }
   }
   else
   {
    if (currentPointArray.Count == 0)
     return;
    isChecking = true;
    if (currentLineList.Count + 1 != currentPointArray.Count)
    {
     //最后一条线的终点不在点上
     //两点一线,点的个数-1等于线的条数
     currentLineList.Remove(currentLine); //从已记录的线集合中删除最后一条多余的线
     canvasRoot.Children.Remove(currentLine); //从界面上删除最后一条多余的线
     currentLine = null;
    }

    if (Operation == ScreenUnLockOperationType.Check)
    {
     Console.WriteLine("playAnimation Check");
     var result = CheckPoint(); //执行图形检查
              //执行完成动画并触发检查事件
     PlayAnimation(result, () =>
     {
      if (OnCheckedPoint != null)
      {
       this.Dispatcher.BeginInvoke(OnCheckedPoint, this, new CheckPointArgs() { Result = result }); //触发检查完成事件
      }
     });

    }
    else if (Operation == ScreenUnLockOperationType.Remember)
    {
     Console.WriteLine("playAnimation Remember");
     RememberPoint(); //记忆绘制的坐标
     var args = new RememberPointArgs() { PointArray = this.PointArray };
             //执行完成动画并触发记忆事件
     PlayAnimation(true, () =>
     {
      if (OnRememberPoint != null)
      {
       this.Dispatcher.BeginInvoke(OnRememberPoint, this, args); //触发图形记忆事件
      }
     });
    }
   }
  }

判断线是否经过了附近的某个点


/// 
  /// 两点计算一线的长度
  /// 
  /// 
  /// 
  /// 
  private double GetLineLength(double x1, double y1, double x2, double y2)
  {
   return Math.Sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); //根据两点计算线段长度公式 √((x1-x2)²x(y1-y2)²)
  }

  /// 
  /// 判断线是否经过了某个点
  /// 
  /// 
  /// 
  private Ellipse IsOnLine()
  {
   double lineAB = 0; //当前画线的长度
   double lineCA = 0; //当前点和A点的距离 
   double lineCB = 0; //当前点和B点的距离
   double dis = 0;
   double deciation = 1; //允许的偏差距离
   lineAB = GetLineLength(currentLine.X1, currentLine.Y1, currentLine.X2, currentLine.Y2); //计算当前画线的长度

   foreach (Ellipse ellipse in ellipseList)
   {
    if (currentPointArray.Contains(ellipse.Tag.ToString())) //排除已经经过的点
     continue;
    var ellipseCenterPoint = GetCenterPoint(ellipse); //取当前点的中心点
    lineCA = GetLineLength(currentLine.X1, currentLine.Y1, ellipseCenterPoint.X, ellipseCenterPoint.Y); //计算当前点到线A端的长度
    lineCB = GetLineLength(currentLine.X2, currentLine.Y2, ellipseCenterPoint.X, ellipseCenterPoint.Y); //计算当前点到线B端的长度
    dis = Math.Abs(lineAB - (lineCA + lineCB)); //线CA的长度+线CB的长度>当前线AB的长度 说明点不在线上
    if (dis <= deciation) //因为绘制的点具有一个宽度和高度,所以需设定一个允许的偏差范围,让线靠近点就命中之(吸附效果)
    {
     return ellipse;
    }
   }
   return null;
  }

检查点是否正确,按数组顺序逐个匹配之


/// 
  /// 检查坐标点是否正确
  /// 
  /// 
  private bool CheckPoint()
  { 
         //PointArray:正确的坐标值数组
         //currentPointArray:当前绘制的坐标值数组
   if (currentPointArray.Count != PointArray.Count)
    return false;
   for (var i = 0; i < currentPointArray.Count; i++)
   {
    if (currentPointArray[i] != PointArray[i])
     return false;
   }
   return true;
  }

记录经过点,并创建一条新的线


/// 
  /// 记录经过的点
  /// 
  /// 
  private void OnAfterByPoint(Ellipse ellipse)
  {
   var ellipseCenterPoint = GetCenterPoint(ellipse);
   currentLine.X2 = ellipseCenterPoint.X;
   currentLine.Y2 = ellipseCenterPoint.Y;
   currentLine = CreateLine();
   currentLine.X1 = currentLine.X2 = ellipseCenterPoint.X;
   currentLine.Y1 = currentLine.Y2 = ellipseCenterPoint.Y;
   currentPointArray.Add(ellipse.Tag.ToString());
   Console.WriteLine(string.Join(",", currentPointArray));
   currentLineList.Add(currentLine);
   canvasRoot.Children.Add(currentLine);
  }


/// 
  /// 获取原点的中心点坐标
  /// 
  /// 
  /// 
  private Point GetCenterPoint(Ellipse ellipse)
  {
   Point p = new Point(Canvas.GetLeft(ellipse) + ellipse.Width / 2, Canvas.GetTop(ellipse) + ellipse.Height / 2);
   return p;
  }

当绘制完成时,执行完成动画并触发响应模式的事件


/// 
  /// 执行动画
  /// 
  /// 
  private void PlayAnimation(bool result, Action callback = null)
  {
   Task.Factory.StartNew(() =>
   {
    this.Dispatcher.Invoke((Action)delegate
    {
     foreach (Line l in currentLineList)
      l.Stroke = result ? rightColor : errorColor;
     foreach (Ellipse e in ellipseList)
      if (currentPointArray.Contains(e.Tag.ToString()))
       e.Fill = result ? rightColor : errorColor;
    });
    Thread.Sleep(1500);
    this.Dispatcher.Invoke((Action)delegate
    {
     foreach (Line l in currentLineList)
      this.canvasRoot.Children.Remove(l);
     foreach (Ellipse e in ellipseList)
      e.Fill = Color;
    });
    currentLine = null;
    this.currentPointArray.Clear();
    this.currentLineList.Clear();
    isChecking = false;
   }).ContinueWith(t =>
   {
    try
    {
     if (callback != null)
      callback();
    }
    catch (Exception ex)
    {
     Console.WriteLine(ex.Message);
    }
    finally
    {
     t.Dispose();
    }
   });
  }

图形解锁的调用


 
      
       
        
       
       
        
       
      
     

相关专题

更多
Java编译相关教程合集
Java编译相关教程合集

本专题整合了Java编译相关教程,阅读专题下面的文章了解更多详细内容。

11

2026.01.21

C++多线程相关合集
C++多线程相关合集

本专题整合了C++多线程相关教程,阅读专题下面的的文章了解更多详细内容。

4

2026.01.21

无人机驾驶证报考 uom民用无人机综合管理平台官网
无人机驾驶证报考 uom民用无人机综合管理平台官网

无人机驾驶证(CAAC执照)报考需年满16周岁,初中以上学历,身体健康(矫正视力1.0以上,无严重疾病),且无犯罪记录。个人需通过民航局授权的训练机构报名,经理论(法规、原理)、模拟飞行、实操(GPS/姿态模式)及地面站训练后考试合格,通常15-25天拿证。

16

2026.01.21

Python多线程合集
Python多线程合集

本专题整合了Python多线程相关教程,阅读专题下面的文章了解更多详细内容。

1

2026.01.21

java多线程相关教程合集
java多线程相关教程合集

本专题整合了java多线程相关教程,阅读专题下面的文章了解更多详细内容。

4

2026.01.21

windows激活码分享 windows一键激活教程指南
windows激活码分享 windows一键激活教程指南

Windows 10/11一键激活可以通过PowerShell脚本或KMS工具实现永久或长期激活。最推荐的简便方法是打开PowerShell(管理员),运行 irm https://get.activated.win | iex 脚本,按提示选择数字激活(选项1)。其他方法包括使用HEU KMS Activator工具进行智能激活。

2

2026.01.21

excel表格操作技巧大全 表格制作excel教程
excel表格操作技巧大全 表格制作excel教程

Excel表格操作的核心技巧在于 熟练使用快捷键、数据处理函数及视图工具,如Ctrl+C/V(复制粘贴)、Alt+=(自动求和)、条件格式、数据验证及数据透视表。掌握这些可大幅提升数据分析与办公效率,实现快速录入、查找、筛选和汇总。

6

2026.01.21

毒蘑菇显卡测试网站入口 毒蘑菇测试官网volumeshader_bm
毒蘑菇显卡测试网站入口 毒蘑菇测试官网volumeshader_bm

毒蘑菇VOLUMESHADER_BM测试网站网址为https://toolwa.com/vsbm/,该平台基于WebGL技术通过渲染高复杂度三维分形图形评估设备图形处理能力,用户可通过拖动彩色物体观察画面流畅度判断GPU与CPU协同性能;测试兼容多种设备,但中低端手机易卡顿或崩溃,高端机型可能因发热降频影响表现,桌面端需启用独立显卡并使用支持WebGL的主流浏览器以确保准确结果

25

2026.01.21

github中文官网入口 github中文版官网网页进入
github中文官网入口 github中文版官网网页进入

github中文官网入口https://docs.github.com/zh/get-started,GitHub 是一种基于云的平台,可在其中存储、共享并与他人一起编写代码。 通过将代码存储在GitHub 上的“存储库”中,你可以: “展示或共享”你的工作。 持续“跟踪和管理”对代码的更改。

7

2026.01.21

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Git 教程
Git 教程

共21课时 | 2.9万人学习

Django 教程
Django 教程

共28课时 | 3.3万人学习

React 教程
React 教程

共58课时 | 3.9万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号