简体   繁体   中英

Make FontSize from Xamarin Forms Picker dynamically

I am creating a Xamarin Forms app and using a picker. I want to change the size of the text but the default text sizes are too small (Title, Body, Large etc.). Then I just tried with size (FontSize = "35") only on some Android devices the text comes out of the grid. Is there a way to keep the size dynamic and inside the grid without using the default options of Xamarin (Title, Body, Large etc.)? Thank you very much

Due to phone devices have different screen densitys, if you set the hardcode font size, it will reslut of showing large effects on devices with small Screen density.

Therefore, you could based on a Screen density to set the based font size, and it will update on different devices.

  • First of all, you will use MVVM to bind font size for View.

  • Second, you can set font size depends on Screen Density in ViewModel.

Using Xamarin.Essentials to get Screen Density:

// Get Metrics
var mainDisplayInfo = DeviceDisplay.MainDisplayInfo;
// Screen density
var density = mainDisplayInfo.Density;
// such as setting basic density be 2 , needed font size be 35
// then set font size as follows
var fontSize =  35 * (mainDisplayInfo.Density/2) ;

For example, the model as follows:

public class Item
{
    public double MyTextFont { set; get; }

    public Item(double fontSize)
    {
        // Get Metrics
        var mainDisplayInfo = DeviceDisplay.MainDisplayInfo;
        // Screen density
        var density = mainDisplayInfo.Density;
        // such as setting basic density be 2 , needed font size be 35
        // then set font size as follows
        MyTextFont = fontSize * (mainDisplayInfo.Density / 2);
    }
}

ContentPage.cs used as follows:

// Set font size be 35 when init Item
Item item = new Item(35);
BindingContext =  item;

Xaml code:

<Label Text="Start developing now" FontSize="{Binding MyTextFont }"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM