UIImage resizableImageWithCapInsets - 可以使用nib指定吗?

时间:2012-09-27 00:03:20

标签: ios ios5 uiimageview uiimage

我使用resizableImageWithCapInsets完美地调整了UIImage的大小,以制作包含文字标签的徽章。我有兴趣知道有没有办法在故事板或用笔尖创建的视图中执行此操作?

没有技术理由要求这样做。大多数UI都是在笔尖中完成的,我希望尽可能多地保存,而不是加载图像,使其可调整大小,查找文本尺寸,调整UIImageView的大小,然后在代码中应用标签。

我不能让这个项目仅限iOS6(部署目标ios5 +),所以使用布局约束不是一种选择。

1 个答案:

答案 0 :(得分:6)

是的,有。

诀窍是覆盖-initWithCoder:和图像设置器(setImage:forState:setBackgroundImage:forState:)以创建您在xib中设置的相同图像的可调整大小的版本。显然,它们仍然无法在xib本身中正确调整大小,但在初始化后它将正确调整大小。不要忘记将NAResizableButton设置为UIButton的自定义类。

当然可以通过编程方式进行。 :)

<强>接口

#import <UIKit/UIKit.h>

@interface NAResizableButton : UIButton

@end

<强>实施

#import "NAResizableButton.h"

@implementation NAResizableButton

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self)
    {
        [self setImage:[self imageForState:UIControlStateNormal] forState:UIControlStateNormal];
        [self setImage:[self imageForState:UIControlStateHighlighted] forState:UIControlStateHighlighted];
        [self setImage:[self imageForState:UIControlStateSelected] forState:UIControlStateSelected];
        [self setImage:[self imageForState:UIControlStateDisabled] forState:UIControlStateDisabled];

        [self setBackgroundImage:[self backgroundImageForState:UIControlStateNormal] forState:UIControlStateNormal];
        [self setBackgroundImage:[self backgroundImageForState:UIControlStateHighlighted] forState:UIControlStateHighlighted];
        [self setBackgroundImage:[self backgroundImageForState:UIControlStateSelected] forState:UIControlStateSelected];
        [self setBackgroundImage:[self backgroundImageForState:UIControlStateDisabled] forState:UIControlStateDisabled];
    }
    return self;
}

- (void)setImage:(UIImage *)inImage forState:(UIControlState)inState
{
    UIEdgeInsets edgeInsets = UIEdgeInsetsMake(ceilf(inImage.size.height / 2), ceilf(inImage.size.width / 2), ceilf(inImage.size.height / 2), ceilf(inImage.size.width / 2));
    if ([inImage respondsToSelector:@selector(resizableImageWithCapInsets:)])
    {
        // iOS 5
        inImage = [inImage resizableImageWithCapInsets:edgeInsets];
    }
    else
        inImage = [inImage stretchableImageWithLeftCapWidth:edgeInsets.left topCapHeight:edgeInsets.top];

    [super setImage:inImage forState:inState];
}

- (void)setBackgroundImage:(UIImage *)inImage forState:(UIControlState)inState
{
    UIEdgeInsets edgeInsets = UIEdgeInsetsMake(ceilf(inImage.size.height / 2), ceilf(inImage.size.width / 2), ceilf(inImage.size.height / 2), ceilf(inImage.size.width / 2));
    if ([inImage respondsToSelector:@selector(resizableImageWithCapInsets:)])
    {
        // iOS 5
        inImage = [inImage resizableImageWithCapInsets:edgeInsets];
    }
    else
        inImage = [inImage stretchableImageWithLeftCapWidth:edgeInsets.left topCapHeight:edgeInsets.top];

    [super setBackgroundImage:inImage forState:inState];
}

@end