Home Backend Development C#.Net Tutorial ScreenUnLock-detailed explanation on the use of graphic unlock control

ScreenUnLock-detailed explanation on the use of graphic unlock control

Aug 11, 2017 pm 01:27 PM
use Detailed explanation

This article mainly introduces the use of WPF graphic unlocking control ScreenUnLock in detail. It has certain reference value. Interested friends can refer to

ScreenUnLock and pattern unlocking on smartphones. Functions are the same. The purpose of unlocking or memorizing graphics is achieved by drawing graphics.

I had a sudden idea to transplant the graphics unlocking function on my mobile phone to WPF. It has also been applied to the company's projects.

Before creating ScreenUnLock, let’s first analyze the implementation idea of ​​graphic unlocking.

1. Create the origin of the nine-square grid (or more grids), and define a coordinate value for each point

2. Provide extended attributes and events related to graphic unlocking to facilitate the definition of the caller. For example: color of points and lines (Color), operation mode (Check|Remember), correct color for verification (RightColor), color for failed verification (ErrorColor), unlock event OnCheckedPoint, memory event OnRememberPoint, etc.;

3. Define the MouseMove event to monitor the line drawing behavior. The line drawing part is also the core of this article. During the line drawing process. The program needs to determine from which point the line starts to be drawn and which point it passes through (excluding already recorded points). Whether the drawing is completed and so on.

4. Line drawing completion, the line drawing completion behavior is processed according to the operation mode. And call related custom events

The general idea is as above, let’s start writing ScreenUnLock step by step

Create ScreenUnLock


public partial class ScreenUnlock : UserControl
Copy after login

Define related properties


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

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

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

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

  /// <summary>
  /// 当前坐标点集合
  /// </summary>
  private IList<string> currentPointArray;

  /// <summary>
  /// 当前线集合
  /// </summary>
  private IList<Line> currentLineList;

  /// <summary>
  /// 点集合
  /// </summary>
  private IList<Ellipse> ellipseList;

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

  public static readonly DependencyProperty OperationPorperty = DependencyProperty.Register("Operation", typeof(ScreenUnLockOperationType), typeof(ScreenUnlock), new FrameworkPropertyMetadata(ScreenUnLockOperationType.Remember));
  /// <summary>
  /// 操作类型
  /// </summary>
  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));
  /// <summary>
  /// 坐标点大小 
  /// </summary>
  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();
  })));

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

     /// <summary>
     /// 操作类型
     /// </summary>
     public enum ScreenUnLockOperationType
     {
      Remember = 0, Check = 1
     }
Copy after login

Initialize 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<string>();
   currentLineList = new List<Line>();
   ellipseList = new List<Ellipse>();
   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();
  }
Copy after login

Create point


/// <summary>
  /// 创建点
  /// </summary>
  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);
    }
   }
  }
Copy after login

Create line


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

The points and lines have been created and defined, and you can start listening for drawing events


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); //触发图形记忆事件
      }
     });
    }
   }
  }
Copy after login

Judge whether the line passes through a nearby point


/// <summary>
  /// 两点计算一线的长度
  /// </summary>
  /// <param name="pt1"></param>
  /// <param name="pt2"></param>
  /// <returns></returns>
  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)²)
  }

  /// <summary>
  /// 判断线是否经过了某个点
  /// </summary>
  /// <param name="ellipse"></param>
  /// <returns></returns>
  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;
  }
Copy after login

Check whether the points are correct and match them one by one in array order


/// <summary>
  /// 检查坐标点是否正确
  /// </summary>
  /// <returns></returns>
  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;
  }
Copy after login

Record passing points and create a new line


/// <summary>
  /// 记录经过的点
  /// </summary>
  /// <param name="ellipse"></param>
  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);
  }
Copy after login


/// <summary>
  /// 获取原点的中心点坐标
  /// </summary>
  /// <param name="ellipse"></param>
  /// <returns></returns>
  private Point GetCenterPoint(Ellipse ellipse)
  {
   Point p = new Point(Canvas.GetLeft(ellipse) + ellipse.Width / 2, Canvas.GetTop(ellipse) + ellipse.Height / 2);
   return p;
  }
Copy after login

When the drawing is completed, the completion animation is executed and Events that trigger response mode


/// <summary>
  /// 执行动画
  /// </summary>
  /// <param name="result"></param>
  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();
    }
   });
  }
Copy after login

Calls for graphics unlock


<local:ScreenUnlock Width="500" Height="500"
      PointArray="{Binding PointArray, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
      Operation="Check"> <!--或Remember-->
      <i:Interaction.Triggers>
       <i:EventTrigger EventName="OnCheckedPoint">
        <Custom:EventToCommand Command="{Binding OnCheckedPoint}" PassEventArgsToCommand="True"/>
       </i:EventTrigger>
       <i:EventTrigger EventName="OnRememberPoint">
        <Custom:EventToCommand Command="{Binding OnRememberPoint}" PassEventArgsToCommand="True"/>
       </i:EventTrigger>
      </i:Interaction.Triggers>
     </local:ScreenUnlock>
Copy after login

The above is the detailed content of ScreenUnLock-detailed explanation on the use of graphic unlock control. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What software is crystaldiskmark? -How to use crystaldiskmark? What software is crystaldiskmark? -How to use crystaldiskmark? Mar 18, 2024 pm 02:58 PM

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

How to download foobar2000? -How to use foobar2000 How to download foobar2000? -How to use foobar2000 Mar 18, 2024 am 10:58 AM

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

How to use NetEase Mailbox Master How to use NetEase Mailbox Master Mar 27, 2024 pm 05:32 PM

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

How to use Baidu Netdisk app How to use Baidu Netdisk app Mar 27, 2024 pm 06:46 PM

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Teach you how to use the new advanced features of iOS 17.4 'Stolen Device Protection' Teach you how to use the new advanced features of iOS 17.4 'Stolen Device Protection' Mar 10, 2024 pm 04:34 PM

Apple rolled out the iOS 17.4 update on Tuesday, bringing a slew of new features and fixes to iPhones. The update includes new emojis, and EU users will also be able to download them from other app stores. In addition, the update also strengthens the control of iPhone security and introduces more "Stolen Device Protection" setting options to provide users with more choices and protection. "iOS17.3 introduces the "Stolen Device Protection" function for the first time, adding extra security to users' sensitive information. When the user is away from home and other familiar places, this function requires the user to enter biometric information for the first time, and after one hour You must enter information again to access and change certain data, such as changing your Apple ID password or turning off stolen device protection.

See all articles