图像下的Xamarin自定义ButtonRenderer文本 [英] Xamarin Custom ButtonRenderer Text under Image
问题描述
我试图将Label放在按钮内的图像下方并居中。我为按钮提供了一个自定义渲染器,但是由于某些原因,我无法生成所需的输出。该代码在C#Xamarin中。
I am trying to place Label under the image inside a button and center it. I have a custom renderer for the button but for some reason I can not produce the desired output. The code is in C# Xamarin.
XAML代码:
<Controls:ExtendedButton
VerticalOptions="EndAndExpand"
HorizontalOptions="CenterAndExpand"
x:Name="search"
Text="Search"
Image="Completed.png"
IsEnabled="{Binding IsLoading}"
Command="{Binding SearchCommand}"
WidthRequest ="120"
HeightRequest ="120"
TextColor="#FFFFFF"
>
</Controls:ExtendedButton>
C#iOS CustomRenderer
C# iOS CustomRenderer
public class ExtendedButtonRenderer : ButtonRenderer
{
UIButton btn;
protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
{
base.OnElementChanged(e);
if (e.OldElement == null)
{
btn = (UIButton)Control;
CGRect imageFrame = btn.ImageView.Frame;
imageFrame.Y = 0;
imageFrame.X = (btn.Frame.Size.Width / 2) - (imageFrame.Size.Width / 2 );
btn.ImageView.Frame = imageFrame;
var labelSize = new NSString(btn.TitleLabel.Text).
GetBoundingRect(
new CGSize(btn.Frame.Width, float.MaxValue),
NSStringDrawingOptions.UsesLineFragmentOrigin,
new UIStringAttributes() { Font = UIFont.SystemFontOfSize(8) },
null);
CGRect titleLabelFrame = new CGRect(labelSize.X, labelSize.Y, labelSize.Width, labelSize.Height);
titleLabelFrame.X = (btn.TitleLabel.Frame.Size.Width / 2) - (labelSize.Width / 2);
titleLabelFrame.Y = (btn.ImageView.Frame.Y ) + (btn.ImageView.Frame.Size.Height) + 20;
btn.TitleLabel.Frame = titleLabelFrame;
}
}
所需的输出
DesiredOutput
+-----------+
| |
| (Image) |
| Label |
| |
+-----------+
推荐答案
仅供参考,对于子孙后代,现在 Xamarin.Forms
Button类支持属性 ContentLayout
,值:上,下,左,右(图像位置)。因此,对于所需的输出,您可以使用本机Button:
Just FYI, and for future generations, Xamarin.Forms
Button class support property ContentLayout
now, with values: Top, Bottom, Left, Right (position of image). So for your desired output you can use native Button:
<Button
ContentLayout="Top"
VerticalOptions="EndAndExpand"
HorizontalOptions="CenterAndExpand"
x:Name="search"
Text="Search"
Image="Completed.png"
IsEnabled="{Binding IsLoading}"
Command="{Binding SearchCommand}"
WidthRequest ="120"
HeightRequest ="120"
TextColor="#FFFFFF"
/>
我不记得在哪里找到此信息,但请参阅 Button.cs 和 ButtonRenderer.cs
I couldn't remember where I found this information, but see Button.cs and ButtonRenderer.cs
这篇关于图像下的Xamarin自定义ButtonRenderer文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!