Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to not stretch an image in UIButton

I'm trying to create a custom UITableViewCell programmatically and one of the subviews of this cell is going to be a button with an image in it (a simple image of a magnifying glass). However, I want the button's image to be centered and scaled proportionately down to fit in the button and NOT to be stretched to fill the entire button. Below is my code where self refers to the custom UITableViewCell which I am placing the button into.

self.myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [self.myButton setBackgroundImage:[UIImage imageNamed: @image_name_here"] forState:UIControlStateNormal]; self.myButton.frame = CGRectMake(...//something, something) self.myButton.imageView.contentMode = UIViewContentModeCenter; [self.contentView addSubview:self.mySearchHelpButton]; 

Right now the image stretches to fill the entire button rather than scaling proportionately so that it fits nicely.

I have also tried setting the contentMode to UIViewContentModeScaleAspectFill but this doesn't seem to change anything. In fact, none of the different contentModes seem to change anything.

like image 956
Nosrettap Avatar asked Jul 05 '12 14:07

Nosrettap


People also ask

How do you center an image in UIButton?

You must set the content mode for the image inside the UIButton. The solution is to update the contentMode of the Image when you are using a foreground image inside a button along with the contentMode of the UIButton .


1 Answers

Have you tried setImage instead of setBackgroundImage?

like image 185
Robot Woods Avatar answered Sep 28 '22 02:09

Robot Woods