Sabai Phoo
Sabai Phoo

Reputation: 368

Responsive Font Size in Xamarin Forms

How can we make responsive font size in Xamarin forms like this in bootstrap?
If it is a smaller device, show small font,
if it is a larger device, then show large font size.

Is there any NuGet package or work source for that?

Upvotes: 2

Views: 3918

Answers (3)

kiddailey
kiddailey

Reputation: 3664

In my experience, I don't believe there is currently a way to do truly responsive design natively in Xamarin. Hopefully this will improve with Maui, but we will have to wait and see. The issues are:

  • NamedFontSizes are not scaled. In other words, on a larger device while the size will be larger due to density/size, it won't be proportionally larger thus resulting in fonts sometimes being too small.

  • OnIdiom may work in some circumstances, but this doesn't address the issue of differences between phones.

The only thing I've found that gets close to what you're looking for is carolzbnbr's OnScreenSize markup extension, which is available on NuGet as "OnScreenSizeMarkup.Forms" or "OnScreenSizeMarkup.Maui."

carolzbnbr wrote a blog entry about it entitled "Adaptive layouts for different device sizes in Xamarin apps"

The extension categorizes screen sizes into named sizes based on their dimensions (using Xamarin.Essentials) and then adds the ability to specify unique values based on those sizes like so:

<Label 
    Text="Sample Text" 
    FontSize="{markups:OnScreenSize DefaultSize=Large, Medium=Large, Large=50, ExtraLarge=70}" 
/>

I should also mention that you aren't limited to using this with FontSize. You can use it many places and even adjust values for left/top/right/bottom using single quotes:

<label Margin="{markups:OnScreenSize DefaultSize='20,60,20,20', ExtraLarge='40'}" />

Upvotes: 1

George Isaac
George Isaac

Reputation: 589

You don't need any NuGet package for this. If you want to set different sizes for phones and tabs you can do this.

<Label Text = "Hello"
FontSize = "{OnIdiom Phone = 20 Tablet = 72}" />

Xamarin scales the font size as the unit is device-independent.

Upvotes: 1

Mihail Duchev
Mihail Duchev

Reputation: 4821

You don't need any package for this. The functionality is built-in deep into Xamarin.Forms.

According to the Xamarin's documentation for the Font sizes:

The size value is measured in device-independent units. For more information, see Units of measurement

If you open the Units of measurement link, you will see that:

Xamarin.Forms uses a platform-independent unit of measurement that normalizes units across devices and platforms. There are 160 units per inch, or 64 units per centimeter, in Xamarin.Forms.

Also, if you look through the already predefined Named font sizes, you will see that there are some differences for each built-in size. This is exactly what is happening under the hood - Xamarin is "scaling" the font size accordingly, taking into account the device's dimensions.

Upvotes: 1

Related Questions