Xamarin 表单:Webview 内容默认大小太小

Xamarin forms: Webview content default size is too small

我正在使用 webview 自定义渲染器来显示 UI 上的 HTML 数据。 webview内容的默认大小太小了。

我的代码:

MyWebView.cs

public  class MyWebView : WebView
{
    public static readonly BindableProperty UrlProperty = BindableProperty.Create(
    propertyName: "Url",
    returnType: typeof(string),
    declaringType: typeof(MyWebView),
    defaultValue: default(string));

    public string Url
    {
        get { return (string)GetValue(UrlProperty); }
        set { SetValue(UrlProperty, value); }
    }
}

MyWebViewRenderer.cs 在 ios

public class MyWebViewRenderer : ViewRenderer<MyWebView, WKWebView>
{
    WKWebView _wkWebView;

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

        if (Control == null)
        {
            var config = new WKWebViewConfiguration();
            _wkWebView = new WKWebView(Frame, config);
            SetNativeControl(_wkWebView);
        }
    }

    protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        base.OnElementPropertyChanged(sender, e);

        if (e.PropertyName == "Url")
        {
            Control.LoadHtmlString(Element.Url, null);
        }
    }
}

XAML 和 XAML.cs

    <local:MyWebView 
    x:Name="web_view"
    HorizontalOptions="FillAndExpand"
    VerticalOptions="FillAndExpand">
</local:MyWebView>

web_view.Url = "htmldata";

输出截图

文本和视频尺寸很小,我没有看到任何增加 webview 字体大小的选项,请提出解决此问题的方法。

您可以为WKWebView添加NavigationDelegate来修改webview的字体大小。

如下:

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

    if (Control == null)
    {
        var config = new WKWebViewConfiguration();
        _wkWebView = new WKWebView(Frame, config);
        _wkWebView.NavigationDelegate = new MyNavigationDelegate();
        SetNativeControl(_wkWebView);
    }
}

public class MyNavigationDelegate : WKNavigationDelegate
{
    public override void DidFinishNavigation(WKWebView webView, WKNavigation navigation)
    {
        string fontSize = "200%"; // > 100% shows larger than previous
        string stringsss = string.Format("document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '{0}'", fontSize);
        WKJavascriptEvaluationResult handler = (NSObject result, NSError err) =>
        {
            if (err != null)
            {
                System.Console.WriteLine(err);
            }
            if (result != null)
            {
                System.Console.WriteLine(result);
            }
        };
        webView.EvaluateJavaScript(stringsss, handler);
        //base.DidFinishNavigation(webView, navigation);
    }

}

默认效果:

200%效果:

=================================更新=========== =======================

如果想让Html的每个元素都压缩,可以在内容Html前加一个header样式。

如下:

string headerString = "<header><meta name='viewport' content='width=device-width, initial-scale=2.0, maximum-scale=5.0, minimum-scale=1.0, user-scalable=no'><style>img{max-width:100%}</style></header>";
string finalHtml = headerString + baseHtml ; //baseHtml is current loaded Html
...

比如可以修改headerString里面的initial-scale的值,下面是示例效果:

string headerString = "<header><meta name='viewport' content='width=device-width, initial-scale=1.5, maximum-scale=5.0, minimum-scale=1.0, user-scalable=no'><style>img{max-width:100%}</style></header>";
string bodyString = "<html><body><h1>Xamarin.Forms</h1><p>Welcome to WebView.</p><video src='movie.ogg'controls='controls'></video></body></html>";
string finalHtml = headerString + bodyString;
...

initial-scale=1.0效果:

initial-scale=1.5效果:

=================================更新=========== =======================

如果想要视频的宽度适合屏幕,我建议从 Html 源代码中处理。因为 HtmlCSS 样式可以使用。例如,如果 Video 添加 style='width:100%;' 在 Html 中,视频将适合屏幕宽度如下:

Html的完整代码:

string bodyString = "<html><body><h1>Xamarin.Forms</h1><p>Welcome to WebView.</p><video style='width:100%;' src='movie.ogg'controls='controls'></video></body></html>";

==============================更新============== ==================

如果无法修改Html的代码,也可以用WKNavigationDelegate从html得到videoobject来修改它们的值。

如下:

public class MyNavigationDelegate : WKNavigationDelegate
{
    public override void DidFinishNavigation(WKWebView webView, WKNavigation navigation)
    {
        // 100% width
        string stringHtml =  "var objs = document.getElementsByTagName('video');for(var i=0; i<objs.length; i++) { objs[i].style.width='100%';} ";
        WKJavascriptEvaluationResult handler = (NSObject result, NSError err) =>
        {
            if (err != null)
            {
                System.Console.WriteLine(err);
            }
            if (result != null)
            {
                System.Console.WriteLine(result);
            }
        };
        webView.EvaluateJavaScript(stringHtml, handler);
    }

}