Arun Dev
Arun Dev

Reputation: 27

UIButton with resizable Image

Ok guys,

i know i am doing something wrong, but i cannot figure that out. here is the code that will put the resizable image for the normal button state.

self.loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.loginButton.frame = CGRectMake(0.0, 44.0, 314, 44);
    UIImage *image = [[UIImage imageNamed:@"loginbutton_image"] resizableImageWithCapInsets:UIEdgeInsetsMake(0.0,10.0,0.0,10.0)];
    [self.loginButton setImage:image forState:UIControlStateNormal];
    [self addSubview:self.loginButton];

Here is the image

enter image description here

either the image asset is wrong or the code.

the image is of 21 px width. the cap inset of 10 & 10 on left right leaves 1Px to resize.

does any one spot what i am doing wrong.

thanks all for stopping by Arun

Upvotes: 1

Views: 4694

Answers (2)

tomidelucca
tomidelucca

Reputation: 2543

you should do it this way:

self.loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.loginButton.frame = CGRectMake(0.0, 44.0, 314, 44);
UIImage *image = [[UIImage imageNamed:@"loginbutton_image"] resizableImageWithCapInsets:UIEdgeInsetsMake(0.0,10.0,0.0,10.0)];
[self.loginButton setBackgroundImage:image forState:UIControlStateNormal];
[self.view addSubview:self.loginButton];

This way you are setting the background image property of the button. The background image is already attached to the button view, so no need to addSubview.

Upvotes: 10

Jesse Gumpo
Jesse Gumpo

Reputation: 4787

try

self.loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.loginButton.frame = CGRectMake(0.0, 44.0, 314, 44);
    UIImage *image = [[UIImage imageNamed:@"loginbutton_image"] stretchableImageWithLeftCapWidth:10 topCapHeight:10]; //assuming the height is 44
    [self.loginButton setImage:image forState:UIControlStateNormal];
    [self addSubview:self.loginButton];

Upvotes: 0

Related Questions