Xamarin Custom ButtonRenderer Text under Image

2019-09-09 21:18发布

问题:

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 Code:

              <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

     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   |
|           |
+-----------+

回答1:

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"
/>

I couldn't remember where I found this information, but see Button.cs and ButtonRenderer.cs



回答2:

I would use fact that UIButton supports already supports an UIImage along with the Title text, you just need to adjust the ImageEdgeInsets and TitleEdgeInsets and set to the x/y alignments to center.

public class CenterImageButtonRenderer : ButtonRenderer
{
    public CenterImageButtonRenderer() { }

    protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
    {
        base.OnElementChanged(e);

        if (e.NewElement != null)
        {
            if (Control != null)
            {
                Control.VerticalAlignment = UIControlContentVerticalAlignment.Center;
                Control.HorizontalAlignment = UIControlContentHorizontalAlignment.Center;

                #if DEBUG
                // Set the border so we can see button bounds on a white background for testing alignment
                Control.Layer.CornerRadius = 15;
                Control.Layer.BorderWidth = 5;
                Control.Layer.BorderColor = UIColor.Red.CGColor;
                #endif

                // The button image is not availabe due to lazy load, so we load "again", get the bounds and dispose of it... :-(
                var uiImage = UIImage.FromFile(((Button)e.NewElement).Image.File);
                var lineHeight = Control.TitleLabel.Font.LineHeight;
                Control.ImageEdgeInsets = new UIEdgeInsets(-lineHeight, uiImage.Size.Width + (uiImage.Size.Width / 2), 0, 0);
                Control.TitleEdgeInsets = new UIEdgeInsets(uiImage.Size.Height, -uiImage.Size.Width, 0, 0);
                uiImage.Dispose();
            }
        }
    }
}

So assuming:

var button = new CenterImageButton
{
    Text = "StackOverflow",
    Image = "so.png"
};

The result is: