开发者

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. Wh开发者_运维百科en 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?


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.


@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.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜