简体   繁体   中英

Xamarin Forms Zoom in Zoom out in Web view Does not work Smoothly

I an Custom Render Webview In that I load a Pdf. When that Pdf is trying to zoom in or zoom out. I can clearly see lacking. Frist, I thought it's the android problem then I download pdf and try it It's okay it runs smoothly.

Here my code

In the shared Project

  public class CustomWebView : WebView
{
    public static readonly BindableProperty UriProperty = BindableProperty.Create(nameof(Uri),typeof(string),typeof(CustomWebView),default(string));

    public string Uri
    {
        get => (string)GetValue(UriProperty);
        set => SetValue(UriProperty, value);
    }       
}

In anrioid Custom Render Like this

  public class CustomWebViewRenderer : WebViewRenderer
{
    public CustomWebViewRenderer(Context context) : base(context)
    {
    }

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

        if (e.NewElement != null)
        {              
            Control.Settings.AllowUniversalAccessFromFileURLs = true;                   
            Control.Settings.BuiltInZoomControls = true;
            Control.Settings.DisplayZoomControls = true;

        }
        this.Control.SetBackgroundColor(Android.Graphics.Color.Transparent);
    }
    protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName != "Uri") return;
        var customWebView = Element as CustomWebView;
        if (customWebView != null)
        {
            Control.LoadUrl(string.Format("file:///android_asset/pdfjs/web/viewer.html?file={0}", string.Format("file:///android_asset/Content/{0}", WebUtility.UrlEncode(customWebView.Uri))));        
        }
    }

}

It's getting the pdf and also it's showing without problem but when zoom in or out clearly can see the latching How to solve this latching problem.

The zoom in/out function in Webview is not smooth

you can either make a custom renderer or use Xam.Plugin.WebView plugin for javascript injection.below is the code showing an example using a plugin. you can call action to zoom in and out.

        var zoomFactor = 0.1;
        var zoomCounter = 1;
        Func<Task> zoomInAction = async () =>
        {
            zoomFactor = zoomFactor + 0.1;
            if (webView != null)
                await webView.InjectJavascriptAsync($"document.body.style.zoom = {zoomCounter + 1 * zoomFactor};");
        };

        Func<Task> zoomOutAction = async () =>
        {
            zoomFactor = zoomFactor - 0.1;
            if (webView != null)
                await webView.InjectJavascriptAsync($"document.body.style.zoom = {zoomCounter + 1 * zoomFactor};");
        };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM