视图大小更改时字体不更改

时间:2019-10-25 22:22:04

标签: c# xamarin xamarin.forms fonts

我正在设置一个主屏幕,该屏幕可以引导到其他部分并进行交互,但是一切正常,但是在较小的屏幕尺寸下,按钮上方标题的测试切换为两行,然后开始与按钮重叠。

我已经写了一些尝试来尝试使字体在屏幕变化时改变大小,但是似乎没有任何作用。我正在编辑的标签是公共标签,因此应该更改吗? Broken Output Image

void OnContentViewSizeChanged(object sender, EventArgs args)
{
    ContentView view = (ContentView)sender;
    // Portrait mode
    if (view.Width > view.Height)
    {
        view.WidthRequest = view.Height;
        view.HeightRequest = view.Height;
    }
    else
    {
        view.HeightRequest = view.Width;
        view.WidthRequest = view.Width;
    }
    //Do FontCalc for button Text
    FontCalc buttonTextLowerFontCalc = new FontCalc(buttonTextLabel, 10, view.Width);
    FontCalc buttonTextupperFontCalc = new FontCalc(buttonTextLabel, 100, view.Width);

    while (buttonTextupperFontCalc.FontSize - buttonTextLowerFontCalc.FontSize > 1)
    {
        double fontSize = (buttonTextLowerFontCalc.FontSize + buttonTextupperFontCalc.FontSize) / 2;

        FontCalc newFontCalc = new FontCalc(buttonTextLabel, fontSize, view.Width);

        if(newFontCalc.TextHeight > view.Height)
        {
            buttonTextupperFontCalc = newFontCalc;
        }
        else
        {
            buttonTextLowerFontCalc = newFontCalc;
        }
    }

    buttonTextLabel.FontSize = buttonTextLowerFontCalc.FontSize;
    buttonTextLabel.Text = buttonTextLabel.Text.Replace("??", buttonTextLabel.FontSize.ToString("F0"));

    //Do FontCalc for title Text
    FontCalc titleTextLowerFontCalc = new FontCalc(titleTextLabel, 10, view.Width);
    FontCalc titleTextupperFontCalc = new FontCalc(titleTextLabel, 100, view.Width);

    while (titleTextupperFontCalc.FontSize - titleTextLowerFontCalc.FontSize > 1)
    {
        double fontSize = (titleTextLowerFontCalc.FontSize + titleTextupperFontCalc.FontSize) / 2;

        FontCalc newFontCalc = new FontCalc(titleTextLabel, fontSize, view.Width);

        if (newFontCalc.TextHeight > view.Height)
        {
            titleTextupperFontCalc = newFontCalc;
        }
        else
        {
            titleTextLowerFontCalc = newFontCalc;
        }
    }

    titleTextLabel.FontSize = titleTextLowerFontCalc.FontSize;
    titleTextLabel.Text = titleTextLabel.Text.Replace("??", titleTextLabel.FontSize.ToString("F0"));
}

struct FontCalc
{
    public FontCalc(Label label, double fontSize, double containerWidth)
    {
        FontSize = fontSize;

        label.FontSize = fontSize;
        SizeRequest sizeRequest = label.Measure(containerWidth, Double.PositiveInfinity);

        TextHeight = sizeRequest.Request.Height;
    }
    public double FontSize { private set; get; }
    public double TextHeight { private set; get; }
}

字体大小应在屏幕大小更改时更改,但不更改。没有错误

0 个答案:

没有答案