Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton with fixed size custom image

I have a custom UIButton as follows:

 UIButton * action = [UIButton buttonWithType:UIButtonTypeCustom];
        [action setSize:CGSizeMake(30, 30)];
    [action setBackgroundImage:[UIImage imageNamed:@"contextaction.png"] forState:UIControlStateNormal];
    [action setContentMode:UIViewContentModeCenter];
    [action addTarget:self action:@selector(actionButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

The real image that I have is actually sized at 10x10, centered and I want it to stay that way and not scaled to the button size. How do I do that?

REVISED CODE:

UIButton * action = [UIButton buttonWithType:UIButtonTypeCustom];
    [action setSize:CGSizeMake(44, 44)];
    [action setImage:[UIImage imageNamed:@"contextaction.png"] forState:UIControlStateNormal];
    [action addTarget:self action:@selector(actionButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

    if (IS_IPAD){
        action.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        action.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    }
     actionButton_ = [[UIBarButtonItem alloc] initWithCustomView:action];

which is still scaling

like image 528
adit Avatar asked Mar 14 '12 22:03

adit


2 Answers

for this i think you need to make use of the image insets property UIButton Class Reference

like image 118
borrrden Avatar answered Sep 29 '22 21:09

borrrden


Use the setImage:forState: method of UIButton instead of setBackgroundImage:forState:

UIButton inherits from UIControl, so you can set the contentHorizontalAlignment and contentVerticalAlignment properties to UIControlContentHorizontalAlignmentCenter and UIControlContentVerticalAlignmentCenter, respectively (although in most cases these are already the default values).

like image 36
sho Avatar answered Sep 29 '22 20:09

sho