UIButton Programmatically (SetImage content Adjustement)
I开发者_StackOverflow中文版 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,
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
精彩评论