如何在界面构建器中设置stretchableImageWithLeftCapWidth?

8
你如何在界面构建器中设置stretchableImageWithLeftCapWidth?
5个回答

9

Interface Builder不支持可拉伸图片。

-(void) viewDidLoad {
  [super viewDidLoad];
  [myImageView setImage:[[myImageView image] stretchableImageWithLeftCapWidth:5 topCapHeight:5 ]];
}

抱歉,但它支持可拉伸的图像。在我的回答中提到了“拉伸”部分扮演了这个角色。 - samthui7

2

目前(截至版本4.5),这是 InterfaceBuilder 的一个限制。然而,为每个按钮创建一个 IBOutlet 并在 viewDidLoad 中手动指定图像可拉伸并不是一个好的解决方案,因为这样做会使 UI 设计更加繁琐且易出错。

相反,我们可以创建一个 UIButton 子类,它默认将任何背景图像设为可拉伸。在这个示例中,我只拉伸了正常和高亮状态的背景图像。对于一个生产就绪的类,您可能需要检查所有状态的前景和背景图像,并将它们拉伸。

@implementation NTSTButton

- (id) initWithCoder:(NSCoder *)aDecoder {

    self = [super initWithCoder:aDecoder];
    if (self) {
        /* There is no support in IB for stretchable images. So, let's
           make sure _any_ background image assigned to this button 
           stretches correctly.
           Note: Setting the stretch cap to 10px, which should work with
           almost all button background images. 
        */
        UIImage *normalImage = 
                 [[self backgroundImageForState:UIControlStateNormal]
                        stretchableImageWithLeftCapWidth:10 topCapHeight:10] ;

        UIImage *highlightedImage = 
                 [[self backgroundImageForState:UIControlStateHighlighted]
                        stretchableImageWithLeftCapWidth:10 topCapHeight:10] ;

        [self setBackgroundImage:normalImage 
              forState:UIControlStateNormal];

        [self setBackgroundImage:highlightedImage 
              forState:UIControlStateHighlighted];
    }
    return self;
}

@end

0
类似于 @answerbot,但已更新为 iOS 5.0+,因为 stretchableImageWithLeftCapWidth:topCapHeight: 已被弃用。
@implementation UIButtonStretchable

- (id) initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self setBackgroundImage: [[self backgroundImageForState:UIControlStateNormal] resizableImageWithCapInsets:UIEdgeInsetsMake(22,6,22,6)]forState:UIControlStateNormal];
        [self setBackgroundImage: [[self backgroundImageForState:backgroundImageForState:UIControlStateHighlighted] resizableImageWithCapInsets:UIEdgeInsetsMake(22,6,22,6)]forState:backgroundImageForState:UIControlStateHighlighted];
    }
    return self;
}
@end

0

0

View 部分使用 Stretching 配置。

  • 首先,将视图模式更改为 Aspect fill

  • 然后在 Stretching 部分编辑 X、Y、宽度、高度字段。 例如:假设您有一个图像大小为 10x20,并希望将其适配到视图大小为 5x10 ==> 设置 X = 5/10 = 0.5,Y = 10/20 = 0.5

注意:IB 不允许您使用较小的图像“拉伸”到更大的框架中,因此您需要尽可能地设计您的图像较大。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接