Forum Xamarin.Forms

How to handle different screen sizes

xWeSTxWeST USMember ✭✭

Hi,

are there any tutorials for xamarin forms on how to handle different screen sizes for iOS, Android and Windows Phone 8 ?
The only tutorials I could found was about apple and android watch.

Tagged:

Best Answer

Answers

  • PaulDistonPaulDiston USUniversity ✭✭✭✭

    What kind of "handling" are you looking to do?

  • xWeSTxWeST USMember ✭✭

    I'm working on a cross-platform app which looks good on one emulator with one resolution. But let's say I wan't to test the App on a bigger or smaller screen. For example the App looks good on iPhone 6 but on iPhone 5 everything is displaced. Or it looks good on a 4,7" android display but not on a 5,5". And the same for Windows Phone. So I just want to figure out how to handle that it looks good on different resolutions. (Tablets are not required yet).
    I know if you do it native with iOS you can handle it with constraints on the storyboard in Xcode. But how do I do that on Xamarin?
    Hope its clear what I mean.

    Thanks :)

  • PaulDistonPaulDiston USUniversity ✭✭✭✭

    Are you writing a Xamarin Forms application? If so there are certain Layout containers which will assist you greatly with differing resolutions.

  • xWeSTxWeST USMember ✭✭
    edited November 2016

    Thanks for your answers

    @ClintStLaurent I gave it a short try and it looks like its correct what you said. Thanks for that.
    But I have two other questions.

    First: if I want to make big labels, I can do it with FontSize="Large" and it will be scaled depending on the screen size. But what if "Large" is not big enough? Let's say someting like FontSize="38" this will not scaled down on small screen. Is there a possibility to say I want bigger lables but they should scaled to fit in one line on smaller screens?

    And the second question:
    When I did the research for this scaling problem, I found this: https://developer.xamarin.com/guides/android/application_fundamentals/resources_in_android/part_4_-_creating_resources_for_varying_screens/
    So it's a bit confusing, if the UI will be handled by the layouts, why is there the possibility to create different files for different screen sizes on xamarin.android?

    Thanks for your help.

  • RussellCollinghamRussellCollingham GBUniversity ✭✭

    You can do something like this

    var msglabel.FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label)) * 2;

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭

    @RussellCollingham said:
    You can do something like this

    var msglabel.FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label)) * 2;

    Two problems. (1) That's in C# in code behind. So just bad practice all around. (2) There's nothing dynamic about it. There's no accounting for screen size etc.

    @wdouble said:

    Is there a possibility to say I want bigger lables but they should scaled to fit in one line on smaller screens?

    And the second question:
    When I did the research for this scaling problem, I found this: https://developer.xamarin.com/guides/android/application_fundamentals/resources_in_android/part_4_-_creating_resources_for_varying_screens/
    So it's a bit confusing, if the UI will be handled by the layouts, why is there the possibility to create different files for different screen sizes on xamarin.android?

    UI is a complex topic and there's no getting around that. Part of that problem is that everyone has a different idea of what "good" should look like.

    Given your desire to set a size, but have it change dynamically depending on screen size I think I'd probably make a converter so you can do binding from your XAML.

    So let's say you want a given size, generally speaking. But under certain rules you want that to change. If you make a converter that takes a size as the ConverterParameter you can then compute a new value on the fly. Since its a converter it is reusable by many controls and not in UI code behind.

    I haven't tested this, and you'll have to do some work too, to get the screen width. But this demonstrates what I mean.

        public class FontSizeConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                try
                {
                    var incomingSize = (double) parameter;
                    double outgoingSize = incomingSize; // For starters
    
                    // Let's apply some rules
                    if (screenWidth > 2400) outgoingSize *= 2.00;
                    else if (screenWidth > 1440) outgoingSize *= 1.75;
                    else if (screenWidth > 1020) outgoingSize *= 1.25;
                    //between 800-1020 we'll do nothing
                    else if (screenWidth < 800) outgoingSize *= .75;
    
                    return outgoingSize;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"GET Error {ex.Message}");
                }
                return value;
            }
    
            public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                throw new NotImplementedException();
            }
        }
    

    Add it to your ResourceDictionary with your other converters

    ...
                <converters:FontSizeConverter x:Key="FontSizeConverter" />
            </ResourceDictionary>
    

    Then use it on your view

                            <Label FontSize="{Binding FontSizeProperty,
                                                      Converter={StaticResource FontSizeConverter},
                                                      ConverterParameter=38}"
                                   Text="Binding SomeStringProperty" />
    
  • RussellCollinghamRussellCollingham GBUniversity ✭✭

    Some people prefer xaml, some people prefer code. Actually I think that the NamedSize.Large does take into account different screen resolutions etc (see https://download.xamarin.com/developer/xamarin-forms-book/XamarinFormsBook-Ch05-Apr2016.pdf)

  • xWeSTxWeST USMember ✭✭

    Thanks for your answers.

    @ClintStLaurent I could reach the result that I wanted with the correct XAML attributes and without hardcoded pixel values. And thanks for the effort, I did not even know that it's possible to work with such converter. I heard about custom renderer but not about converter.

    @RussellCollingham Thanks for your help but I think it's an easy and right way to handle it with XAML and the layouts. I had a short look at the link you postet, for me it sounds like working with code behind for the UI is "only" needed if you need other finishing on the UI wich is not possible with XAML

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭

    @RussellCollingham said:
    Some people prefer xaml, some people prefer code. Actually I think that the NamedSize.Large does take into account different screen resolutions etc (see https://download.xamarin.com/developer/xamarin-forms-book/XamarinFormsBook-Ch05-Apr2016.pdf)

    It should. All sizes and measure are supposed to be in DiP (Device Independent Pixels): So 150 is 150 is 150 regardless of resolution or resolution-density of the device. And the font size is supposed to automatically take into account the user setting for font size magnification set at the OS level. But since the original poster said he needed a way to correct for it, I had to beleive they actually ran tests and saw a problem that needed fixing.

  • DmitryBlackDmitryBlack RUMember ✭✭
                if (screenWidth > 2400) outgoingSize *= 2.00;
    

    An interesting solution. Only it is not clear that this is screenWidth. Where to take its meaning?

  • MJ_AhmedMJ_Ahmed BHMember ✭✭

    @ClintStLaurent said:
    Sounds like you might be trying to micro-manage the layout. Don't set sizes if you don't HAVE to. Let each thing resize itself. Most controls will shrink to a size just big enough for its needs. Controls that hold older controls (such as Grids and StackLayouts) will expand just big enough to hold their children.

    When creating rows and columns in grids, again don not set sizes. Instead set relationships.

                <RowDefinition Height="Auto" />
                <RowDefinition Height="3*" />
                <RowDefinition Height="2*" />
    

    instead of

                <RowDefinition Height="150" />
                <RowDefinition Height="60" />
                <RowDefinition Height="20" />
    

    You have accept you don't have total control over the user's phone. They might have set the system-wide font size to LARGEST for example, because they are 60 years old. There is also the option to 'Bold all text' to make things easier to read but also makes the text just that hair bigger. That means buttons and labels will make themselves wider to accommodate. Your app might be deployed on a French device so some of the words might be longer than the English version.

    Hi, what is the meaning of the asterisk in the height value?

  • SchmickeySchmickey Member

    @MJ_Ahmed said:

    Hi, what is the meaning of the asterisk in the height value?

    Asterisk means give me what is left. So if the window height is 800 and the autos take up 400 then the asterisk takes up the remaining 400.
    If there are 2 elements with *, then they both get equal amounts; further if there is one 2* and one * then the 2* gets 2/3rds of the remaining display and the * gets 1/3rd of the remaining display.

  • SteveShaw.5557SteveShaw.5557 USMember ✭✭✭
    edited May 2018

    @DmitryBlack

    screenWidth

    In free eBook "Xamarin Forms Book", chapter 5 there is a good discussion of working with different screens.

    Every Xamarin.Forms.View object has properties Width and Height, though these are not set until after page layout.
    A good time to call them is when SizeChanged event occurs; then you know they have been set to valid values.

    In that book, look for source code of public WhatSizePage() pages 91-92. There we see adding a handler to SizeChanged event. In your page's constructor put this line:

    SizeChanged += OnPageSizeChanged;
    

    which refers to this method:

    void OnPageSizeChanged(object sender, EventArgs args)
    {
        label.Text = String.Format("{0} \u00D7 {1}", Width, Height);
    }
    

    where label is a name you have given to a label on that page.
    In XAML, label could be defined this way:

    <Label x:Name="label"/>
    

    (The book shows how to define the label in code; do one OR the other, not both ways.)


    IMPORTANT: Width and Height are in "device independent units" (DIU), approximately 160 per inch (64 per centimeter).
    Xamarin Forms takes care of screens with high pixel density, by using DIU.
    So if you ask for a given font size, whether by a numeric size (12) or a name (Small),
    it will be approximately the same physical size on the screen.

    But what if a device is physically larger, rather than having higher pixel density?
    That is when Width and Height numbers become larger.
    So, a value of "640" DIU would be 640 / "160 per inch" = 4 inches.
    A value of "1280" DIU would be 1280 / 160 = 8 inches.
    Again, these are approximate physical sizes.

    This is why ClintStLaurent's code example might be useful:
    If Width and Height values are larger on one device, that means the device is physically larger.
    Now, you must decide whether you want to keep your content (e.g. text) the same size,
    fitting more on the screen, or make it larger.

    I tend to take a "middle way". Unless I'm displaying a lot of text, like a news article,
    I make the font size "somewhat larger" on a larger device.
    My reasoning:

    • A larger device might be held farther from the eyes.
    • Squeeze info on small device, so enough fits to be useful,
      on a larger device, make it more "comfortable", easier to read.

    However, I don't completely scale up to the size of the device, because then everything is huge.
    So might squeeze to 12-14 diu on 4" screen (iPhone 5s), 16 diu on 5" screen, 20-24 (or more) diu on 9"+ screen (tablet).
    list of screen sizes of popular devices

Sign In or Register to comment.