Issue
I would like to resize the text inside my button based on the size of my button. How can I do it?
<Button StyleClass="btnFAF" Text="Field Activity" Grid.Row="0" Grid.Column="0" x:Name="btnFAF" Clicked="btnFAF_Clicked" BorderRadius="6">
<Button.FontFamily>
<OnPlatform x:TypeArguments="x:String">
<On Platform="Android" Value="OpenSans-Regular.ttf#OpenSans-Regular"/>
</OnPlatform>
</Button.FontFamily>
</Button>
Solution
You can use the custom renderer
In Forms:
public MainPage() {
InitializeComponent();
Content = new StackLayout {
Children = {
new MyButton {
Text="XXXXXXXXXXXXX",
WidthRequest=50,
HeightRequest=20
}
},
VerticalOptions = LayoutOptions.CenterAndExpand,
HorizontalOptions = LayoutOptions.CenterAndExpand,
};
}
And you can define a subclass of Button:
namespace App11 {
public class MyButton:Button {
public MyButton() {
}
}
}
In iOS:
[assembly: ExportRenderer(typeof(MyButton), typeof(MyiOSButton))]
namespace xxx.iOS {
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;
}
}
}
}
In Android:
[assembly:ExportRenderer(typeof(MyButton),typeof(MyAndroidClass))]
namespace _1111111.Droid {
public class AutoFitButton:Android.Widget.Button {
public AutoFitButton(Context context):base(context) {
}
protected override void OnDraw(Canvas canvas) {
base.OnDraw(canvas);
SetAutoSizeTextTypeWithDefaults(AutoSizeTextType.Uniform);
}
}
public class MyAndroidClass:ButtonRenderer {
IElementController ElementController => Element as IElementController;
public MyAndroidClass(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);
}
}
}
Notice:the method SetAutoSizeTextTypeWithDefaults(AutoSizeTextType.Uniform)
is only available after Android O (API 26).
Answered By - Lucas Zhang - MSFT
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.