Have you ever wanted to add a WebView to your Xamarin Forms app and make it’s background transparent ? Let’s say you need to display some custom Text Label’s or some custom control with loads of customization to it’s content or sub controls ?
Whereas your first solution would be to go for a WebView control, but you need to make that WebView Transparent to match the background color of the page ? If you had gone through or going through such requirements, then this article is for you.
WebView for Fancy Stuff…
We all know WebView is usually used for displaying Web Content right ? but then also we could use it to display complicated customized text or content, but then there is one problem, matching the Page background to the WebView control, because it’s impossible to set the background transparent of the WebView in Xamarin Forms.
Yeah you guess right! Custom Renderers for the RESCUE! WOOT!
So here is how I implemented my Transparent WebView with life-saving Custom Renderers in Xamarin Forms.
So as usual we need to sub-class the default Xamarin Forms WebView control with our Transparent WebView control as follows.
So as of our Android implementation we need to access the native control counterpart for the Xamarin Forms WebView using the WebViewRenderer.
We access the Control property which holds the native Android WebView control which deals with the Xamarin Forms WebView. As you can see above we set the Control Background color to Transparent through SetBackgroundColor() method. BOOM! You are good to go with Android!
Now let’s dive into iOS, well its the same as Android, the trick is to set the Control’s background color to Transparent.
But also we need to set the Opaque property to false as show above, otherwise the control wouldn’t render as transparent. Then as usual we set the BackgroundColor property.
So let’s try it out!
Too lazy to try it out ?😛 No worry, I would probably be bored to try it out unless I actually need to. haha.
So here goes the sample implementation, if you have implemented the above properly, then use the below test code and run your app!
You can see below, I’m setting the Page’s background color to Red and the StackLayout’s background color to Yellow. Now the WebView should be rendered as Transparent and the Yellow background should be visible.🙂
BOOM! THERE YOU GO!😀
Alright! Now go crazy with it fellas!