UIButton - 只在一个方向上可拉伸的背景图像?

时间:2011-11-21 10:52:34

标签: ios uibutton uiimage custom-controls

我有一个UIButton对象,我在其中使用可伸缩图像作为背景,因此我总是可以使用灵活的按钮大小。

问题是我希望有一个固定的高度图像(例如32px),但想要有一个更高的可触摸区域(Apple UI准则说总是至少44px高)。

如果我在x中有一个可伸缩的图像,不幸的是它也会延伸到y。我想告诉图像不要拉伸。这可能吗?

[编辑]是的,确实如此。回答我自己的问题:

1 个答案:

答案 0 :(得分:3)

所以,只是为了帮助别人,我可以回答我自己的问题:

@interface StretchableXButton : UIButton
{
    CGFloat imageHeight;
}
@property CGFloat imageHeight;  // we need this later when we override an instance method

+ (id)buttonWithFrame:(CGRect)frame;

@end

现在执行:

@implementation StretchableXButton
@synthesize imageHeight; 

+ (id)buttonWithFrame:(CGRect)frame
{
    StretchableXButton *button = [super buttonWithType:UIButtonTypeCustom];

    UIImage *normalImage = [UIImage imageNamed: @"ButtonBGNormal.png" ];
    UIImage *highlightedImage = [UIImage imageNamed:@"ButtonBGHighlighted.png" ];

    button.frame = frame;
    button.imageHeight = normalImage.size.height;  // we need him later in the method below

    // make the images stretchable
    normalImage = [normalImage stretchableImageWithLeftCapWidth:normalImage.size.width/2 topCapHeight:normalImage.size.height/2];
    highlightedImage = [highlightedImage stretchableImageWithLeftCapWidth:normalImage.size.width/2 topCapHeight:normalImage.size.height/2];

    button.backgroundColor = [UIColor clearColor];

    // SET OTHER BUTTON PROPERTIES HERE (textLabel, fonts, etc.)

    [button setBackgroundImage:normalImage forState:UIControlStateNormal];
    [button setBackgroundImage:highlightedImage forState:UIControlStateHighlighted];

    return  button;
}

// THIS IS THE TRICK.  We make the height of the background rect match the image.
-(CGRect)backgroundRectForBounds:(CGRect)bounds
{
    CGRect bgRect = bounds;
    bgRect.origin.y = (bounds.size.height - imageHeight)/2.0f;
    bgRect.size.height = imageHeight;

    return bgRect;
}


@end