First of all, I am using Xamarin iOS.
Whenever I try to set an image of a UIButton, the image gets as big as the entire screen. I want that image to fit into the bounds/ frame of the UIButton.
I have tried using PDF images and PNG images (image in the screenshot is a png). Both of them ignore the frame and size of the actual UIButton they're embedded in.
Here is what the UIButton looks in the xcode storyboard. It is aligned to the vertical and horizontal middle of the superview, has a width of 0.25x the superview and an aspect ratio of 1:1. I also tried giving it a fixed height and width but that didn't help.
I debugged the frame size but found out that it stays constant and isn't affected by the UIButtons Image.
To summarize everything I've tried so far and doesn't work:
public partial class ViewController : UIViewController
{
public ViewController(IntPtr handle) : base(handle)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
// 1.
Btn.SetImage(UIImage.FromBundle("skip"), UIControlState.Normal);
// 2.
Btn.SetBackgroundImage(UIImage.FromBundle("skip"), UIControlState.Normal);
// 3.
Btn.ContentMode = UIViewContentMode.ScaleAspectFill;
Btn.ContentMode = UIViewContentMode.ScaleAspectFit;
Btn.ImageView.ContentMode = UIViewContentMode.ScaleAspectFill;
Btn.ImageView.ContentMode = UIViewContentMode.ScaleAspectFit;
// 4.
Btn.ImageEdgeInsets = new UIEdgeInsets(100, 100, 100, 100);
Btn.ContentEdgeInsets = new UIEdgeInsets(100, 100, 100, 100);
// 5.
UIImage image = UIImage.FromBundle("skip");
image.CreateResizableImage(new UIEdgeInsets(10, 10, 10, 10));
Btn.SetImage(image, UIControlState.Normal);
// 6.
image.Scale(new CGSize(Btn.Frame.Width, Btn.Frame.Height), 0.1f);
Btn.SetImage(image, UIControlState.Normal);
}
}
This problem exists on all devices I tested on the simulator (IPhone 11, IPhone 12, IPhone 12 mini, IPod touch). I could not test it on a real device yet.
It seems like nobody else on the internet has this problem. What am I missing? It probably is something trivial but I can not figure it out.
Thanks in advance
I'm assuming you are using Xcode 13 Storyboard designer.
If so, change the Button Style from "Plain":
to "Default":
Now your image will fit to the constrained button size.