0

I have the following Image Set defined in my Media.xcassets library...

enter image description here

I am loading this image to a button as follows...

    public override void ViewDidLoad()
    {
        base.ViewDidLoad();

        FSDirectButton.SetImage(UIImage.FromBundle("FSDirectButton"), UIControlState.Normal);
    }

However, the button is not the correct size. How do I load an image to a button and then have the button resize to fit the image? I am not sure which image is being picked (1x, 2x, 3x).

enter image description here

John Livermore
  • 30,235
  • 44
  • 126
  • 216

2 Answers2

1

Here is a recipe that I have used in the past that has helped greatly: https://developer.xamarin.com/recipes/ios/standard_controls/buttons/use_an_image_for_a_button/

a few things you may also want to consider trying: 1. Make sure constraints are set so that the button is always the right size 2. If all else fails try adding the images to your resource folder and accessing them as files instead as a temporary workaround. 3. also, you may want to try SetBackgroundImage(), instead of SetImage to see if it yields different results. 4. Try setting the image for all the control states of the button (highlighted, disabled, etc.) 5. try changing the content mode for the imageview inside the button. It may just be that the image is too large and doesn't scale to fit the alloted space. access this by using FSDirectButton.ImageView.ContentMode

To answer your question about which image size is selected (1x, 2x, etc.), I believe that is determined by the resolution of the IOS device that the image is being displayed on. that way if someone uses an iphone or an iPad the image will still look nice and clear without you having to write a lot more code to choose the best image for each device.

DavidShepard
  • 306
  • 3
  • 11
1

How do I load an image to a button and then have the button resize to fit the image?

If you want your button auto resizing to fit its image. Please use Autolayout to layout your button.

Try to add the top constraint and left constraint to define the element's position in X and Y. Then the button will auto adjust its size depending on its content if we don't add the width and height constraint to the button.

I am not sure which image is being picked (1x, 2x, 3x).

After adding the images, the system will decide which image should be picked depending on which device the app run on. we just need to use the image name without the suffix. More details about which device picks which type of image you can refer to this

Ax1le
  • 6,563
  • 2
  • 14
  • 61