一种更轻松的发现文本写作方向的方法 [英] A lighter way of discovering text writing direction

查看:21
本文介绍了一种更轻松的发现文本写作方向的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想确定字符串的书写方向,以便我可以在 CALayer 中正确呈现从右到左的语言,例如阿拉伯语.

I want to determine the writing direction of a string so that I can render Right-to-Left languages such as Arabic correctly in a CALayer.

所以我有这个方法

+(UITextAlignment)alignmentForString:(NSString *)astring
{
    UITextView *text = [[UITextView alloc] initWithFrame:CGRectZero];
    text.text = astring;

    if ([text baseWritingDirectionForPosition:[text beginningOfDocument] inDirection:UITextStorageDirectionForward] == UITextWritingDirectionRightToLeft) {
        return UITextAlignmentRight;
    }

    return UITextAlignmentLeft;

}

工作正常但感觉有点沉重,只是为了发现对齐我的文本的方式,特别是因为它在 drawInContext 中被调用(尽管相对不频繁).

Works fine but feels a little heavy just for the purpose of discovering which way to align my text especially as its been called in drawInContext (although relatively infrequently).

是否有更轻松的方法来确定给定字符串的书写方向,或者我应该在过早优化的基础上坚持下去.而且它必须对 iOS 5 友好.

Is there a lighter way of determining the writing direction for a given string or should I just stick with this under the basis of premature optimisation. And its got to be iOS 5 friendly.

推荐答案

问题中的代码虽然功能性非常昂贵.通过分析器运行它,您会发现当在图层的 drawInContext 方法中使用时,它在 UITextView.setText 中花费了接近 80% 的时间.

The code in the question although functional is brutally expensive. Run it through a profiler and you will find that it spends close to 80% of the time in UITextView.setText when used in the drawInContext method for a layer.

大部分答案都在检测 NSString 的语言

因此更好的形式是...

a better form is thus...

+(UITextAlignment)alignmentForString:(NSString *)astring
{

    if (astring.length) {

        NSArray *rightLeftLanguages = @[@"ar",@"he"];

        NSString *lang = CFBridgingRelease(CFStringTokenizerCopyBestStringLanguage((CFStringRef)astring,CFRangeMake(0,[astring length])));

        if ([rightLeftLanguages containsObject:lang]) {

            return UITextAlignmentRight;

        }
    }

    return UITextAlignmentLeft;

}

因为阿拉伯语和希伯来语是 CFStringTokenizerCopyBestStringLanguage 可以检测到的唯一从右到左的语言,并且还应该涵盖波斯语、乌尔都语和意第绪语,尽管我还没有测试过.

As Arabic and Hebrew are the only Right-to-Left languages detectable by CFStringTokenizerCopyBestStringLanguage and should also cover Persian, Urdu and Yiddish though I havent tested that.

另见http://en.wikipedia.org/wiki/Right-to-左

这篇关于一种更轻松的发现文本写作方向的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆