Xamarin.Forms 手势密码实现

Xamarin.Forms 手势密码实现

在前面的文章中,讲到了Xamarin.Android、Xamarin.iOS、UWP分别实现手势密码功能,现在我们在Xamarin.Forms中来实现这个功能。

  

原理和Xamarin.Android、Xamarin.iOS、UWP一样,关键就是如何使用ViewRenderer。

首先我们新建Xamarin.Forms项目:

在项目中创建GuestureLockView继承View(官方文档: 自定义Renderer)。

接下来分别在Android、iOS、UWP项目中创建GuestureLockViewRenderer

Android中 : GuestureLockViewRenderer继承ViewRenderer<GuestureLockView, Android.Views.View>

iOS中: GuestureLockViewRenderer继承ViewRenderer<GuestureLockView, UIView>

UWP中: GuestureLockViewRenderer继承ViewRenderer<GuestureLockView, CanvasControl>,CanvasControl需要在NuGet中安装Win2D库。

还需要在GuestureLockViewRenderer中重写protected override void OnElementChanged(ElementChangedEventArgs<GuestureLockView> e)方法。

protected override void OnElementChanged (ElementChangedEventArgs<GuestureLockView> e)
{
  base.OnElementChanged (e);

  if (Control == null) {
    // Instantiate the native control and assign it to the Control property with
    // the SetNativeControl method
  }

  if (e.OldElement != null) {
    // Unsubscribe from event handlers and cleanup any resources
  }

  if (e.NewElement != null) {
    // Configure the control and subscribe to event handlers
  }
}

控件在加载时,会调用该方法。原文如下说明:

An overridden version of the OnElementChanged method, in each platform-specific renderer class, is the place to perform the native control instantiation and customization. The SetNativeControl method should be used to instantiate the native control, and this method will also assign the control reference to the Control property.

然后就是在GuestureLockViewRenderer根据各个平台分别绘制图形,这样就能实现该需求了。

在这是实验中,恰巧遇到 Control为null的情况(UWP中),这时需要调用SetNativeControl方法初始化一个NativeControl。

if(Control == null)
{
    SetNativeControl(new CanvasControl());
}

 Github:https://github.com/devinZhou102/Plugin.GuestureLock

 Xamarin.Android手势密码:http://www.cnblogs.com/devin_zhou/p/8057243.html

 Xamarin.iOS手势密码:http://www.cnblogs.com/devin_zhou/p/8047313.html

Xamarin.UWP手势密码:http://www.cnblogs.com/devin_zhou/p/8052305.html

猜你喜欢

转载自www.cnblogs.com/devin_zhou/p/8946436.html