Press "Enter" to skip to content

Overlay view in Xamarin Forms

A year ago we had a particularly interesting UX request from one of our customer’s applications, which was showing an overlay with a transparent shape on top of a camera view. It seemed pretty challenging at the time because we had never worked with showing overlays when the camera is displaying. Today want to share how we accomplished it with a sample that shows this overlay in different scenarios like when using a map or camera..

Here’s what we did

1- Create a new overlay control class

This control will have the following properties:

  • OverlayOpacity: Indicates the overlay opacity.
  • OverlayBackgroundColor: Sets the overlay background color.
  • Shape: Sets the shape type for the overlay.
  • ShowOverlay: Indicates if will show or not the overlay.

We define the enum to support two types of shape: Circle and Heart (why not? is the month of love right!).

2- Create native overlay view in Android

To achieve this on android we draw a bitmap in the View’s canvas. We create this bitmap by using a canvas to draw our overlay outer rectangle and shape inside.

The following line is the one that allows achieving the transparency on our shape:

paint.SetXfermode(new PorterDuffXfermode(PorterDuff.Mode.Clear));

3- Create custom renderer in Android

This renderer allows the mapping between our Forms OverlayView to the Android NativeOverlayView.

4- Create native overlay view in iOS

We use a CAShapeLayer as a sublayer for our custom view to be able to draw the outer and inside path for our overlay using a UIBezierPath.

5- Create custom renderer for iOS

This renderer allows the mapping between our Forms OverlayView to the iOS NativeOverlayView.

By setting UsesEvenOddFillRule on our path to true and setting FillRule on our sublayer to CAShapeLayer.FillRuleEvenOdd allow us to have the transparent shape.

6- Enjoy our cool overlay 🙂

Android

iOS

You can find the full sample source code here.

References:

https://medium.com/@rgomez/android-how-to-draw-an-overlay-with-a-transparent-hole-471af6cf3953

https://stackoverflow.com/questions/9305405/how-to-create-a-mask-for-a-transparent-overlay

https://stackoverflow.com/questions/7007429/android-how-to-draw-triangle-star-square-heart-on-the-canvas/18440622

https://www.appcoda.com/bezier-paths-introduction/

Happy overlay!

3 Comments

  1. Eduardo Eduardo

    Muy bien mi amigo y hermano Rendy. un Saludo especial.

  2. Alberto Silva Alberto Silva

    Thanks for your article, could you please check why the picture is not being shown?

  3. Godfred Boateng Godfred Boateng

    Cool post

Comments are closed.