【问题标题】:How to stretch a UIImage to fit text?如何拉伸 UIImage 以适合文本?
【发布时间】:2012-12-10 08:00:48
【问题描述】:

我正在我的应用程序中实现一个标签系统,为此我需要标签的背景图像和覆盖该图像的文本。问题是 - 我如何拉伸图像以“适合”文本? “数学”可以正常工作,但像“经济学”这样的词就不行,因为它会与背景图像重叠。

这是我的标签的样子:

【问题讨论】:

    标签: iphone objective-c ios xcode uiimage


    【解决方案1】:

    您首先需要计算文本的预期大小,然后相应地为图像赋予框架。如果需要,您可以使用具有大写宽度和大写高度的图像。这是代码sn-p。

        CGSize maximumLabelSize = CGSizeMake(600,52);  // maximum possible size
        CGSize expectedLabelSize = [brandName sizeWithFont:[UIFont fontWithName: @"Helvetica-Bold" size:20] 
                                         constrainedToSize:maximumLabelSize 
                                             lineBreakMode:UILineBreakModeTailTruncation]; 
    
        UIImage *centerStretchedImage =[[UIImage imageNamed:@"yourImage.png"] stretchableImageWithLeftCapWidth:10.0 topCapHeight:0];
    
        CGRect frame = CGRectMake(x, y, expectedLabelSize.width+20,52);
        UIImageView *dynamicImage = [[UIImageView alloc] initWithFrame:frame];
        dynamciImage.image = centerStretchedImage;
    

    【讨论】:

      【解决方案2】:

      您可以找到字符串宽度(在您的情况下可能是 UILabel),如下所示

      CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font 
                              constrainedToSize:maximumLabelSize 
                              lineBreakMode:yourLabel.lineBreakMode]; 
      

      一旦知道文本长度,您就可以使用它并将背景设置为可拉伸图像。

      UIImage *strechableImage = [[UIImage imageNamed:@"tagImage"] resizableImageWithCapInsets:UIEdgeInsetsMake(3, 3, 3, 25)]
      

      Insets(大写字母)是(上、左、下、上)并定义未缩放/拉伸的区域(例如圆角)。

      来自 Apple 文档

      在图像缩放或调整大小期间,被帽子覆盖的区域不会被缩放或调整大小。相反,每个方向上未被帽覆盖的像素区域从左到右和从上到下平铺,以调整图像大小。

      【讨论】:

        【解决方案3】:

        我最好的猜测是使用可拉伸图像,这些只是普通图像,您可以在其中设置 iOS 可以拉伸的部分。

        这些图片很容易制作:

        UIImage *imageTemp = [UIImage imageNamed:@"ButtonBackground.png"];
        
        // For iOS 4.3 and lower
        UIImage *stretchableImage = [imageTemp stretchableImageWithLeftCapWidth:20 topCapHeight:10];
        
        // if you are targetting iOS 5 and higher
        UIImage *stretchableImage = [imageTemp resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 20, 20)];
        

        2010 只是示例,它们对于您的图像可能有所不同。如果这些是UIButton,您可以将可拉伸图像设置为按钮的背景,它会随着按钮正确增长。如果您正在为 UILabel 设置代码中的文本,您可以使用 sizeWithFont:constrainedToSize: 来计算字符串的 with。然后设置正确的图片大小。

        【讨论】:

        • 来自Apple doc stretchableImageWithLeftCapWidth :创建并返回具有指定上限值的新图像对象。 (在 iOS 5.0 中已弃用。已弃用。使用 resizableImageWithCapInsets: 代替,指定 cap insets 以使内部为 1x1 区域。)
        • 是的,你是正确的,但如果你的目标是 iOS 4.3,你可能还想使用stretchableImageWithLeftCapWidth: topCapHeight:
        • 正确,仅当我们的目标是 iOS 4.3 以后。对于 iOS 5.0 及更高版本,已弃用。
        猜你喜欢
        • 2012-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-12
        • 1970-01-01
        • 2011-11-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多