iphone - 如何拉伸(stretch) UIImage 以适合文本?

标签 iphone objective-c ios xcode uiimage

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

这是我的标签的样子:

最佳答案

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

    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;

关于iphone - 如何拉伸(stretch) UIImage 以适合文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13797025/

相关文章:

ios - 将工具栏中的栏按钮放置在 Storyboard的中心(纵向和横向)

iOS 11 - 键盘高度在键盘通知中返回 0

ios - 为 iOS 构建 webrtc 库时出错

iphone - 移除 iOS 6 ScrollView 居中对齐

iphone - 更改 contentSizeForViewInPopover on navigationController push on iOS

IOS - 从应用程序商店安装旧应用程序版本

iphone - 从左侧滑动 View

iphone - 在 Objective-C 中确定属性是否为 int、float、double、NSString、NSDate、NSNumber 等

iphone - 在 iPhone 上接收图像(TCP 客户端)

ios - XCode 5 和 Kiwi/XCUnit 的单元测试问题和崩溃