Xamarin WebView scale image to fit device

EJ 361 Reputation points
2021-05-03T04:10:36.827+00:00

Hi,

We're using Xamarin WebView on both iOS and Android to display emails. If email contains large image it's not scaled to the device width, is there a way to achieve this? If I load same email on Gmail app on the phone then it looks fine, e.g. image is scaled to fit the screen. Want to achieve the same with WebView.

Thanks in advance.

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
4,818 questions
No comments
{count} votes

Accepted answer
  1. 2021-05-04T09:21:06.51+00:00

    Hello,

    Welcome to Microsoft Q&A!

    Try to add custom renderer for each platform to make WebView scale fit to its content.

    iOS
       public class CustomWebViewRenderer : WebViewRenderer  
       {  
           protected override void OnElementChanged(VisualElementChangedEventArgs e)  
           {  
               base.OnElementChanged(e);  
         
               var view = Element as CustomWebView;  
               if (view == null || NativeView == null)  
               {  
                   return;  
               }  
               this.ScalesPageToFit = true;  
           }  
         
       }  
    
    Android
       public class CustomWebViewRenderer : WebViewRenderer  
       {  
           protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)  
           {  
               base.OnElementChanged(e);  
         
               if (Control != null)  
               {  
                   Control.Settings.BuiltInZoomControls = true;  
                   Control.Settings.DisplayZoomControls = false;  
         
                   Control.Settings.LoadWithOverviewMode = true;  
                   Control.Settings.UseWideViewPort = true;  
               }  
           }  
       }  
    

    Refer to https://stackoverflow.com/a/50019749/8187800 .

    Best Regards,
    Cole Xia


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful