一种发现文字书写方向的较轻方式 [英] A lighter way of discovering text writing direction
问题描述
我想确定字符串的书写方向,这样我就可以在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.
另见< a href =http://en.wikipedia.org/wiki/Right-to-left =nofollow noreferrer> http://en.wikipedia.org/wiki/Right-to-left
这篇关于一种发现文字书写方向的较轻方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!