There might be a situation where you want to display an image with pan and zoom functionality. Although you can implement custom renderers with gesture handling, as described in this section about gesture-based interaction, there is a much simpler alternative using a WebView. It is a visual element displaying arbitrary HTML.
Adding a WebView to our MainPage is simple. The most important property is the Source, which is set to a new HtmlWebViewSource.
MainPage = new ContentPage {
Padding = new Thickness(0, Device.OS == TargetPlatform.iOS ? 20 : 0, 0, 0),
Content = new WebView {
Source = new HtmlWebViewSource {
Html = "<html><body><img src=\"xamarin.png\"/></body></html>",
BaseUrl = BaseUrl,
},
},
};
The HTML code contains an image referring to an image file “xamarin.png”. In order to let the WebViewsearch for the file in the correct directory, we need to specify the BaseUrl, which is different depending on the device platform. Therefore, we define a public static property of our App class.
public static string BaseUrl;It is initialized within the platform-specific code:
- On Android – within OnCreate – we set BaseUrl to a constant value.
App.BaseUrl = "file:///android_asset/"; - On iOS – within FinishedLaunching – we initialize the BaseUrl with the main bundle path.
App.BaseUrl = NSBundle.MainBundle.BundlePath;
[assembly:ExportRenderer(typeof(WebView), typeof(ZoomableWebViewRenderer))]
The ZoomableWebViewRenderer is derived from the default WebViewRenderer. It only adjusts two settings related to the zoom controls. It is important to do that within OnElementPropertyChanged (and not within the constructor) and to do a null-check beforehand.
public class ZoomableWebViewRenderer: WebViewRenderer
{
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (Control != null) {
Control.Settings.BuiltInZoomControls = true;
Control.Settings.DisplayZoomControls = false;
}
base.OnElementPropertyChanged(sender, e);
}
}
Now Android uses built-in zoom controls, but does not display additional buttons.