开发者

Clip Image of UIButton

I have a UIButton that uses an image for display.

The problem is that my image is 109x78 but I want the button to be th开发者_Go百科e size of 109x20, pinned to the top left and clipping everything larger then 20 pixel high.

This is what I have now:

UIButton *startTrainingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[startTrainingBtn setContentMode:UIViewContentModeTopLeft];
[startTrainingBtn setClipsToBounds:YES];
[startTrainingBtn setImage:[UIImage imageNamed:@"startTrainingClosed"] forState:UIControlStateNormal];
[startTrainingBtn setFrame:CGRectMake(900, 653, 109, 20)];
[self.view addSubview:startTrainingBtn];

I would have thought that using the ContentMode to TopLeft and ClipsToBounds to YES, would have worked, but instead it is just shrinking the image to fit.


This was asked a year ago and I think you already did what I'm going to tell you but still let me leave this for the record: use a properly sized image then. You have an image which has more than the double of the height you need.

I understand that the behavior seems strange but it's the way the images for the buttons are handled. However you can set the background color to a pattern using your image and it'll have the effect you're after.

UIButton *startTrainingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
startTrainingBtn.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"startTrainingClosed"]];
[startTrainingBtn setFrame:CGRectMake(900, 653, 109, 20)];
[self.view addSubview:startTrainingBtn];

The problem with this solution is that you cannot set a different image for a different state nor have a selected effect on the button.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜