Share on Google+Share on Google+

UIButton Image Size

Advertisement
In this example we are going to discuss about how to set image size and setting image as a UIButton background

UIButton Image Size

In this example we are going to discuss about how to set image size and setting image as a UIButton background.

We are doing it programmatically. Just find the given code...

- (void)viewDidLoad {
[super viewDidLoad];

//Create a button
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
myButton.frame = CGRectMake(80, 50, 70, 70); //set frame for button

//add image on button
UIImage *buttonImage = [UIImage imageNamed:@"home.png"];
//image that is stretchable
UIImage *stretchableButtonImage = [buttonImage stretchableImageWithLeftCapWidth:12 topCapHeight:0];

//set image as background
[myButton setBackgroundImage:stretchableButtonImage forState:UIControlStateNormal];
[self.view addSubview:myButton];

[myButton setTitle:@"Say, Hi!" forState:UIControlStateNormal];
// add targets and actions
[myButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];

}

On running this UIButton code.. you it should look like the given image..

In our code you can see that we are stretching the code... actually in the above code we are creating a image that is stretchable to a particular height and width.
The method can be written as ...

// create a custom image that is stretchable. Note that this might return a new instance of a different class
- (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight;

Download Code

Advertisements

Advertisement

Posted on: May 3, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.