Display an Image based on Screen Orientation

Handling the SizeChanged event

PDF for offline use
Sample Code:
Related APIs:

Let us know how you feel about this

Translation Quality


0/250

This recipe shows how to use Xamarin.Forms to detect the screen orientation and display an image based on the orientation.

Overview

There are a number of approaches that can be used to detect when the screen orientation changes in a Xamarin.Forms app. The simplest approach is to handle the SizeChanged event of the Page. This event fires when either the width or height of the Page changes. Then, an image can be chosen for display by comparing the height and width of the Page.

Detecting Screen Orientation

The following code example shows how to display an image based on the screen orientation:

public partial class HomePage : ContentPage
{
  public HomePage ()
  {
    InitializeComponent ();
    SizeChanged += OnSizeChanged;
  }

  void OnSizeChanged (object sender, EventArgs e)
  {
    image.Source = ImageSource.FromFile (Height > Width ? "portrait.jpg" : "landscape.jpg");
  }
}

The OnSizeChanged event handler sets the Image.Source property to a portrait or landscape image, depending on whether the Height of the ContentPage is greater than the Width of the ContentPage.

Summary

This recipe showed how to use Xamarin.Forms to detect the screen orientation and display an image based on the orientation.

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.