Skip to content

Instantly share code, notes, and snippets.

@Axemasta
Last active May 31, 2019 09:59
Show Gist options
  • Save Axemasta/97b9e85e7756637fcf4c58004017b6dd to your computer and use it in GitHub Desktop.
Save Axemasta/97b9e85e7756637fcf4c58004017b6dd to your computer and use it in GitHub Desktop.
Orientation Aware Content Page
/// <summary>
/// Device Orientation.
/// </summary>
public enum Orientation
{
/// <summary>
/// Portrait Orientation.
/// </summary>
Portrait,
/// <summary>
/// Horizontal Orientation.
/// </summary>
Horizontal
}
public class ContentPageExtended : ContentPage
{
#region Properties
#region - Class Properties
private double _width = 0;
private double _height = 0;
#endregion - Class Properties
#endregion Properties
public ContentPageExtended()
{
}
#region Methods
#region - Overridable Methods
/// <summary>
/// Called when the device orientation changes
/// </summary>
/// <param name="orientation">Orientation.</param>
/// <param name="height">Height.</param>
/// <param name="width">Width.</param>
public virtual void OnOrientationChanged(Orientation orientation, double height, double width)
{
}
#endregion - Overridable Methods
#region - Base Class Methods
//https://spin.atomicobject.com/2018/09/24/xamarin-forms-orientation-changes/
protected override void OnSizeAllocated(double width, double height)
{
base.OnSizeAllocated(width, height);
if (this._width != width || this._height != height)
{
this._width = width;
this._height = height;
var dimensions = GetScreenDimensions();
OnOrientationChanged(dimensions.orientation, dimensions.height, dimensions.width);
}
}
#endregion - Base Class Methods
#region - Helper Methods
/// <summary>
/// Gets the popup dimensions.
/// </summary>
/// <returns>The popup dimensions.</returns>
private (Orientation orientation, double height, double width) GetScreenDimensions()
{
var longestSide = Math.Max(Application.Current.MainPage.Height, Application.Current.MainPage.Width);
var shortestSide = Math.Min(Application.Current.MainPage.Height, Application.Current.MainPage.Width);
bool isPortrait = _height > _width;
if (isPortrait)
{
return (Orientation.Portrait, longestSide, shortestSide);
}
else
{
return (Orientation.Horizontal, shortestSide, longestSide);
}
}
#endregion - Helper Methods
#endregion Methods
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment