I created a UIButton instance named "button" with an image using [UIButton setImage:forState:]
. The button.frame is larger than the image's size.
Now I want to scale this button's image smaller. I tried changing button.imageView.frame
, button.imageView.bounds
and button.imageView.contentMode
, but all seem ineffective.
Can anyone help me scale a UIButton
's imageView?
I created the UIButton
like this:
UIButton *button = [[UIButton alloc] init];
[button setImage:image forState:UIControlStateNormal];
I tried to scale the image like this:
button.imageView.contentMode = UIViewContentModeScaleAspectFit;
button.imageView.bounds = CGRectMake(0, 0, 70, 70);
and this:
button.imageView.contentMode = UIViewContentModeScaleAspectFit;
button.imageView.frame = CGRectMake(0, 0, 70, 70);
An Addition Way for config in XIB file. You can choose this option if you want text or image is Scale full fill in UIButton. It's will be the same with code.
From small test I just did after reading here, depends if you use setImage or setBackgroundImage, both did the same result and strech the image
I can't get a solution use by _imageView, but I can use a
CGContextRef
to solve it. It use theUIGraphicsGetCurrentContext
to get the currentContextRef and draw a image in currentContextRef, and then scale or rotate the image and create a new image. But it's not perfect.the code:
This will also work, as the backgroundImage automatically scales
[button setBackgroundImage:image forState:UIControlStateNormal];
I found this solution.
1) Subclass the following methods of
UIButton
And it works well.