Get current screen width in xamarin forms - xamarin

I am creating one Xamarin Forms project and I got stuck in finding the current screen width according to the different device.
I know how it can be done in android and ios but need a way to find the width in portable.

You can try this Application.Current.MainPage.Width in my case this worked and i am able to find the device width in portable project itself.

I know it is an old thread but worth mentioning that recently Xamarin.Essentials NuGet pakage was released and there is a useful class DeviceDisplay in there that should handle this task for you.
The documentation can be found here.
Usage example:
// Get Metrics
var mainDisplayInfo = DeviceDisplay.MainDisplayInfo;
// Orientation (Landscape, Portrait, Square, Unknown)
var orientation = mainDisplayInfo.Orientation;
// Rotation (0, 90, 180, 270)
var rotation = mainDisplayInfo.Rotation;
// Width (in pixels)
var width = mainDisplayInfo.Width;
// Width (in xamarin.forms units)
var xamarinWidth = width / mainDisplayInfo.Density;
// Height (in pixels)
var height = mainDisplayInfo.Height;
// Screen density
var density = mainDisplayInfo.Density;

Common code (in App.xaml.cs)
public static int ScreenHeight {get; set;}
public static int ScreenWidth {get; set;}
Android part (in MainActivity.cs, in the OnCreate method)
App.ScreenHeight = (int) (Resources.DisplayMetrics.HeightPixels / Resources.DisplayMetrics.Density);
App.ScreenWidth = (int) (Resources.DisplayMetrics.WidthPixels / Resources.DisplayMetrics.Density);
iOS part (in AppDelegate.cs, in the FinishedLaunching method)
App.ScreenHeight = (int)UIScreen.MainScreen.Bounds.Height;
App.ScreenWidth = (int)UIScreen.MainScreen.Bounds.Width;
So App.ScreenHeight and App.ScreenWidth will be initialized when the App will be launched, then you will be able to use them anywhere in the common code.

You can use the Width property when you are in a ContentPage. For example,
protected override void OnAppearing()
{
base.OnAppearing();
double w = this.Width;
}
Note that this is set during the Layout phase. So, you can only use it after the page is initialized, otherwise it is -1.
https://developer.xamarin.com/api/property/Xamarin.Forms.VisualElement.Width/

I would like to create a static struct in the shared code, so I can access the screen width/height values easily (as well as doing bindings in xAML).
The struct in the app namespace (e.g. in App.xaml.cs):
using System;
using Xamarin.Forms;
namespace YourAppName {
...
public struct Constant {
public static double ScreenWidth = Application.Current.MainPage.Width;
public static double ScreenHeight = Application.Current.MainPage.Height;
}
}
Retrieving screen width in C#:
var labelWidth = Constant.ScreenHeight * 0.2;
// then do something with labelWidth
Retrieving screen width in XAML:
<Label Text="Text with insane font size" FontSize="{Binding Source={x:Static local:Constant.ScreenWidth}}"/>

Another approach would be to use the override "OnSizeAllocated" for your page and then take the height and width according to the changes on the user's screen. You can create a static class to set the height and width of your screen everytime it changes and then access them from this class when needed.
The static class to set and access the device dimension:
public static class ScreenDimensions
{
public static double Height { get; set; }
public static double Width { get; set; }
}
Override to obtain the screen dimensions:
protected override void OnSizeAllocated(double width, double height)
{
base.OnSizeAllocated(width, height);
ScreenDimensions.Height = height;
ScreenDimensions.Width = width;
}

I Guess that the best way is use the xamarin.forms.Device information.
Size size = Device.Info.PixelScreenSize;
if (size.Width <= 720 && size.Height <= 1280)
{
stkLayoutTop.Margin = new Thickness(5, 30, 10, 0);
}
else
{
stkLayoutTop.Margin = new Thickness(5, 50, 10, 0);
}

Related

How to convert Xamarin Forms view to a Native view iOS/Android with the same size?

I am using the example here, but I am struggeling to fill in the right size parameter here so that it represents the same size as the forms view.
https://michaelridland.com/xamarin/creating-native-view-xamarin-forms-viewpage/
public static UIView ConvertFormsToNative(Xamarin.Forms.View view, CGRect size)
{
var renderer = RendererFactory.GetRenderer(view);
renderer.NativeView.Frame = size;
renderer.NativeView.AutoresizingMask = UIViewAutoresizing.All;
renderer.NativeView.ContentMode = UIViewContentMode.ScaleToFill;
renderer.Element.Layout(size.ToRectangle());
var nativeView = renderer.NativeView;
nativeView.SetNeedsLayout();
return nativeView;
}
And for Android:
public static ViewGroup ConvertFormsToNative(Xamarin.Forms.View view, Rectangle size)
{
var vRenderer = RendererFactory.GetRenderer (view);
var viewGroup = vRenderer.ViewGroup;
vRenderer.Tracker.UpdateLayout ();
var layoutParams = new ViewGroup.LayoutParams ((int)size.Width, (int)size.Height);
viewGroup.LayoutParameters = layoutParams;
view.Layout (size);
viewGroup.Layout (0, 0, (int)view.WidthRequest, (int)view.HeightRequest);
return viewGroup;
}
}
What values from my Xamarin Forms should be put in, so that it will represent the CGRect required to have the same on the Native View.
var rect = new CGRect();
rect.X = (nfloat)view.X;
rect.Y = (nfloat)view.Y;
rect.Width = (nfloat)view.Width;
rect.Height = (nfloat)view.Height;
Solved it, where "view" is the Xamarin Forms view.

Xamarin change height of progress bar

I am trying to change the height of a progress bar by using a custom renderer like here
The problem is, when the screen is rotated, the progress bar goes back to normal. Can someone help me?
I am using the same solution:
public override void LayoutSubviews()
{
base.LayoutSubviews();
var X = 1.0f;
var Y = 10.0f;
CGAffineTransform transform = CGAffineTransform.MakeScale(X, Y);
this.Control.Transform = transform;
}
I thnk you need to call the command SetNeedsLayout as discussed here . Of course you can also disable orientation change.
public override void OnConfigurationChanged (Android.Content.Res.Configuration newConfig)
{
base.OnConfigurationChanged (newConfig);
SetNeedsLayout ();
}

Xamarin Forms iOS method for screen size is changed

In my Xamrin.Forms app i used this method for get the screen resolution: I wrote an interface with height and width properties and in the iOS rendere I used UIScreen.MainScreen.Bounds.Height and UIScreen.MainScreen.Bounds.Width. And it was ok... until about one month ago! Now, if I run my app on iPhone 5c (screen resolution declared 1136x640) the values are 568x320 whit scale 2 and if I run it on iPhone 6 (resolution declared 1334x750) the values are the same, 568x320 whit scale 2!
Does anybody know what is changed?
Thanks
No need to use dependency service to get device width & height.
Best way to get screen width & height, whenever screen height or width changes or screen is rotated OnSizeAllocated() will get fired and you will get new width & height
sample code :
using Xamarin.Forms;
namespace ABC
{
public class MyPage : ContentPage
{
private double _width;
private double _height;
public MyPage()
{
Content = new Label {
Text = "Welcome to Xamarin.Forms!"
};
}
protected override void OnSizeAllocated(double width, double height)
{
base.OnSizeAllocated(width, height);
_width = width;
_height = height;
}
}
}

Xamarin forms increase ProgressBar height

I have been developing a Xamarin forms application. I want to increase the height of the progress bar control. I used custom renders to change the color of the progress control. But I couldn't find any way to increase the height. Please help me. following is my Custom render class.
public class MyProgressBarRenderer:ProgressBarRenderer
{
protected override void OnElementChanged (
ElementChangedEventArgs<Xamarin.Forms.ProgressBar> e)
{
base.OnElementChanged (e);
Control.ProgressTintColor = Color.FromHex ("#254f5e").ToUIColor();
}
}
Add this override to MyProgressBarRenderer, and adjust Y as necessary....
using UIKit;
using CoreGraphics;
......
public override void LayoutSubviews()
{
base.LayoutSubviews();
var X = 1.0f;
var Y = 5.0f;
CGAffineTransform transform = CGAffineTransform.MakeScale(X,Y);
this.Transform = transform;
}
There is small issue in the iOS renderer code try using
this.Control.Transform = transform;
instead of
this.Transform = transform;

How do you limit the overall height of a ListField?

I'm trying to limit the height of a ListField, so that instead of moving down the screen when you move through the items, you only move down inside the box. So, for example, the header on the screen wouldn't disappear.
My current solution doesn't work. The height doesn't change. It stills stays at whatever size the list of objects is. The code I'm using is:
_listField = new ListField()
{
protected void layout(int w, int h)
{
super.layout(w, 100);
}
};
You can do this way. In your MainScreen constructor add
super(NO_VERTICAL_SCROLL);
so your mainscreen will not scroll.
create new manager which has vertical scrolling enabled so only manager will be scrollable like
VerticalFieldManager listManager = new VerticalFieldManager(VERTICAL_SCROLL | VERTICAL_SCROLLBAR);
Now add your components to this manager say your ListField like
listManager.add(your listfield object);
If you want to limit the height of listField, then you can set the limit to listManger and add the listfield to manager. so list will be layout in given height of manger like this
VerticalFieldManager listManager = new VerticalFieldManager(VERTICAL_SCROLL | VERTICAL_SCROLLBAR);
{
protected void sublayout( int maxWidth, int maxHeight )
{
int width = Display.getWidth();
int height = 100;
super.sublayout( width, height);
setExtent( width, height);
}
};
Hope this will help you.
Take a look at putting the list field inside a MainScreen. Then you can set the header as the title of the MainScreen.

Resources