views:

146

answers:

1

Hi,

I have a simple button and I want to put an image inside, so I have this code:


myButton = [[UIButton alloc] initWithFrame:CGRectMake(20, 13, 116, 138)];

UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[self.visuel lpath] ofType:@"jpg"]];
[myButton setImage:image forState:UIControlStateNormal];

in InterfaceBuilder Its easy to tell my image to take the size and width of my button but how to do that programmatically? do I have to use myButton.contentHorizontalAlignment =..... something like that?

Best Regards,

+1  A: 

What you probably want to do is this...

myButton = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
myButton.frame = CGRectMake(20.0, 13.0, 116.0, 138.0);
UIImage *tImage = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[self.visue1 lpath] ofType:@"jpg"]];
[myButton setBackgroundImage:[tImage stretchableImageWithLeftCapWidth:11 topCapHeight:0] forState:UIControlStateNormal];
[tImage release];

Of course the cap widths will depend on your image. It just repeats the next line of pixels over and over again until your image stretches to the proper width

DougW
I have many images with different size, I don't wanna work with the size all the times, I want to fill my button with the image.Is there no easy way like in the InterfaceBuilder in attributes-->Control-->Content-->H aligenement and V alignement.
ludo
Ok I understand, I just have to put the stretchableImageWithLeftCapWidth: to 0 and the image will be ok.thank you~
ludo