如何在iOS中计算非拉丁语文本宽度?

时间:2015-09-03 06:53:46

标签: ios

我使用以下代码来获取乌尔都语的大小,但它计算的是错误的宽度,请帮我找到乌尔都语字符串的正确宽度。

 CGSize size = [str sizeWithAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"Jameel-Noori-Nastaleeq" size:18.0f]}];

1 个答案:

答案 0 :(得分:0)

尝试以下方法。他们使用CoreText

获取特定文本的高度,约束到特定宽度:

- (CGFloat) heightWithAttributedString:(NSAttributedString*)renderedAttributedText maxWidth:(CGFloat) width {

    if (!renderedAttributedText) {

        return 0.0;
    }

    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFTypeRef)(renderedAttributedText));

    CGSize suggestedSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, 0), NULL, CGSizeMake(width, CGFLOAT_MAX), NULL);

    CFRelease(framesetter);

    return suggestedSize.height;
}

获取特定文本的宽度,约束到特定高度:

- (CGFloat) widthWithAttributedString:(NSAttributedString *)renderedAttributedText maxHeight:(CGFloat)height {

    if (!renderedAttributedText) {

        return 0.0;
    }

    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFTypeRef)(renderedAttributedText));

    CGSize suggestedSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, 0), NULL, CGSizeMake(CGFLOAT_MAX, height), NULL);

    CFRelease(framesetter);

    return suggestedSize.width;
}