Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image vs Background image for UIButton

I have an image that is 480x331 and has a transparent background. The transparent part is just around the image's edges. My UIButton is 72x37. When I set the image as a background image in IB for the button, the transparent edges of the image show as white in the button. Without an image, the button is white with rounded corners. I'm guessing that is the white I see coming through. If so, it means the image transparency is working but the button's white area is showing through.

If I set the image to the UIButton's Image property, it doesn't scale correctly, even after changing view mode, and remains at its full size.

Any suggestions on which property I should use to get the scaling and transparency to work right?

like image 354
4thSpace Avatar asked Dec 04 '25 00:12

4thSpace


2 Answers

What button type are you using?

By the sounds of it you are possibly using the UIButtonTypeRoundedRect style, but UIButtonTypeCustom may be more suitable. You can change this within Interface Builder's inspector window.

like image 104
Christopher Fairbairn Avatar answered Dec 05 '25 13:12

Christopher Fairbairn


@Christopher Fairbaim is right to suggest the use of UIButtonTypeCustom. Using UIButtonTypeRoundedRect will give you the white background in transparent areas.

However, wiring things up in Interface Builder has its limitations. If you want to dynamically generate UIViews, UIButtons, and assets from either a data set or based off of user input, doing so programmatically is the way to go.

To create the button: (Note: this will also work with other UIButtonTypes, but I've used UIButtonTypeCustom for this particular transparency example.)

UIButton *btnName = [UIButton buttonWithType:UIButtonTypeCustom];

To change desired properties:

btnName.backgroundColor = [UIColor clearColor];
btnName.frame = CGRectMake(100, 100, 72, 37);  //(X coord, Y coord, width, height)
[btnName addTarget:myActionClassName action:@selector(myActionName) forControlEvents:UIControlEventTouchUpInside];

To add images for various states (assume these are transparent .png's):

UIImage *btnNameImageNormal = [UIImage imageNamed:@"btnNameNormal.png"];
[btnName setBackgroundImage:btnMenuImageNormal forState:UIControlStateNormal];
UIImage *btnNameImagePressed = [UIImage imageNamed:@"btnNamePressed.png"];
[btnName setBackgroundImage:btnNameImagePressed forState:UIControlStateHighlighted];

To add the button to the view (from within a viewController class):

[self addSubview:btnName];

(Pardon any typos, as I copied and pasted from one of my projects and tried to generalize the naming.)

like image 43
Old McStopher Avatar answered Dec 05 '25 14:12

Old McStopher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!