'Xamarin Forms: Button text font size based on the size of the button
How can I adapt the font size of a button based of the size of the button itself?
Im using Xamarin Forms in the newest version (5.0.0.2337).
Solution 1:[1]
This can be achieved by Custom Renderer
Below is code snippets for your reference:
Code in Xaml:
<local:MyButton Text="My Button" WidthRequest="100" HeightRequest="50"/>
MyButton in Shared Project:
public class MyButton : Button
{
public MyButton()
{
}
}
In Android: MyAndroidButton.cs:
namespace AppHybridWebView.Droid
{
public class MyAndroidButton : ButtonRenderer
{
public MyAndroidButton(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
{
base.OnElementChanged(e);
if (Control != null)
{
SetNativeControl(new AutoFitButton(Context));
}
}
protected override void OnDraw(Canvas canvas)
{
base.OnDraw(canvas);
}
}
public class AutoFitButton : Android.Widget.Button
{
public AutoFitButton(Context context) : base(context)
{
}
protected override void OnDraw(Canvas canvas)
{
base.OnDraw(canvas);
SetAutoSizeTextTypeWithDefaults(AutoSizeTextType.Uniform);
}
}
}
In iOS MyiOSButton.cs:
namespace AppHybridWebView.iOS
{
public class MyiOSButton : ButtonRenderer
{
public MyiOSButton()
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
{
base.OnElementChanged(e);
if (Control != null)
{
Control.TitleLabel.SizeToFit();
Control.TitleLabel.AdjustsFontSizeToFitWidth = true;
}
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alexandar May - MSFT |
