按钮图像未垂直居中

Button image not centering vertically

我已经对按钮进行了子类化,这样我基本上可以获得一个带有圆角边缘和右侧图标的按钮。

几乎做对了,唯一的问题是图标没有垂直居中,似乎无法弄清楚如何影响垂直对齐。

原始图像是矩形的,我正在使用带有预定义 UIEdgeInsets 结构的 CreateResizableImage,如下所示,但我看到的是:

我的子类代码是:

partial class CustomGreyButton : UIButton
    {
        public CustomGreyButton (IntPtr handle) : base (handle)
        {
            this.Layer.BorderColor = new CoreGraphics.CGColor (0, 0, 0);
            this.Layer.BorderWidth = 1;
            this.Layer.CornerRadius = 20;

            // top, left, bottom, right
            UIEdgeInsets btnEdgeInsets = new UIEdgeInsets (0,44,0,44);

            UIImage stretchingButtonImage = new UIImage ("ios_images/grey_btn.png").CreateResizableImage (btnEdgeInsets);


            this.SetBackgroundImage (stretchingButtonImage, UIControlState.Normal);
            this.SetBackgroundImage (stretchingButtonImage, UIControlState.Selected);
            this.SetBackgroundImage (stretchingButtonImage, UIControlState.Highlighted);
            this.ClipsToBounds = true;
            this.AdjustsImageWhenHighlighted = false;

            //this.TitleColor = UIColor.White;
            this.SetTitleColor (UIColor.White, UIControlState.Normal);
            this.SetTitleColor (UIColor.Black, UIControlState.Highlighted);
            this.SetTitleColor (UIColor.Black, UIControlState.Selected);
        }
    }

我在 xamarin forum

上发现了同样的问题

据了解,您应该在图像上放置 YAlign="Center"

经过反复试验发现这似乎适用于我的代码:

UIImage stretchingButtonImage = new UIImage ("ios_images/grey_btn.png");

stretchingButtonImage.ImageWithAlignmentRectInsets (btnEdgeInsets);

看来我不应该使用

CreateResizableImage