【问题标题】:iOS - can stretch a UIImageView but not a UIButton?iOS - 可以拉伸 UIImageView 但不能拉伸 UIButton?
【发布时间】:2011-07-02 10:42:19
【问题描述】:

看:

//UIImageView* stretchTest = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image.png"]];
//[self addSubview:stretchTest];


UIButton *stretchTest = [UIButton buttonWithType:UIButtonTypeCustom];
[stretchTest setFrame:CGRectMake(0, 0, 400, 100)];
[stretchTest setBackgroundImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
[self addSubview:stretchTest];

stretchTest.contentStretch = CGRectMake(0.5, 0.5, 0, 0);
stretchTest.contentMode = UIViewContentModeScaleToFill;

CGRect frame = stretchTest.frame;
frame.size.height = 300;
stretchTest.frame = frame;

使用 UIImageView(上面已注释掉),图像会适当拉伸 - 圆角保持正确的半径,因为只有图像的中心像素会被拉伸。

使用 UIButton,图像被错误地拉​​伸。圆角半径没有保持,变得丑陋。

UIImageView 和 UIButton 都是 UIView 的子类。为什么按钮的调整大小与 imageView 不同?

【问题讨论】:

    标签: ios uiview uiimageview uibutton


    【解决方案1】:

    您正在对 UIButton 的工作方式做出假设。它的实现方式与 UIImageView 不同。 UIImageView 只是一个视图,没有子视图,它的内容是图像。 UIButton 不同,它的工作方式是私有的实现细节。

    如果您尝试在按钮上适当地拉伸图像,您应该使用-[UIImage stretchableImageWithLeftCapWidth:topCapHeight:] 来获取知道应该如何拉伸它的 UIImage。如果您只想拉伸中间像素,可以使用类似

    UIImage *image = [UIImage imageNamed:@"image.png"];
    image = [image stretchableImageWithLeftCapWidth:floorf(image.size.width/2) topCapHeight:floorf(image.size.height/2)];
    

    【讨论】:

    • 好的……那行得通。我之所以尝试使用上述内容,是因为根据 Apple 的说法,“在指定视图的背景时,使用 contentStretch 属性优于创建可拉伸的 UIImage 对象。”他们没有提及 UIView 的哪些子类可以或不能使用该属性。
    • 按钮上的可用 contentStretch 是我已经编写的(现在两次!)一个 UIButton 子类,它将 UIImageViews 插入自身,并将其背景图像(和 contentStretch)复制到其中。这并不难。唯一的小问题是覆盖 LayoutSubviews 以将 imageViews 移到后面,这样它们就会出现在按钮的非背景图像和标题标签后面。
    【解决方案2】:

    UIButton 可以显示两种类型的图像——前景图像和背景图像。按钮的背景图像应替换按钮的背景纹理。因此,它将拉伸以填充整个背景。按钮的前景图像应该是一个图标,可能会或可能不会显示在文本旁边;它不会伸展。如果框架小于图像,它可能收缩,但不会拉伸。

    按钮的前景和背景图像可以用这样的代码设置:

    // stretchy
    [self setBackgroundImage:backgroundImage forState:UIControlStateNormal];  
    
    // not stretchy
    [self setImage:forgroundImage forState:UIControlStateNormal]; 
    

    默认情况下,按钮的backgroundImage 将使用 scaleToFill 来拉伸图像。如果您需要使用 cap insets 拉伸图像,则应在将其分配给 backgroundImage 之前将它们设置在图像上,如下所示:

    UIImage *image = [UIImage imageNamed:@"bg_image.png"];
    
    /* This assumes your image will have a 1px column and 1px row of pixels 
       in the horizontal and vertical middle of the image that should be
       stretchable. If that's not the case (such as asymetrical buttons) 
       you need to adjust the caps */
    image = [image stretchableImageWithLeftCapWidth:floorf(image.size.width/2)
                   topCapHeight:floorf(image.size.height/2)];
    [self setBackgroundImage:image forState:UIControlStateNormal];  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-25
      • 1970-01-01
      相关资源
      最近更新 更多