上标,下标文本与核心文本iPhone



谁能解释我,如何绘制上标和下标字母与核心文本?

谢谢。

我注意到这个问题有点老了,我希望你在这件事上仍然需要帮助,这篇文章将帮助你。

你可以使用NSAttributedString(或它的可变对应的NSMutableAttributedString)来为单个字符串的特定范围分配不同的属性(如字体,名称和大小)。

上标和下标不是核心文本本身支持的,为了使它们看起来很好,你可能需要做很多工作。幸运的是,有一个由Oliver Drobnik从可可遗传学开发的开源项目,允许您轻松地将HTML转换为NSAttributedString(或NSMutableAttributedString),将其输入自定义textview并显示上标和下标(以及许多其他HTML和CSS),因为它们会出现在UIWebview中,但不需要使用UIWebview。你可以从这里下载项目。

虽然这个项目已经投入了很多努力,但有两点需要注意:

    计算有时可能非常性能密集。
  1. 还不支持所有的HTML标签和CSS特性。

如果NSAttributedString是一个可接受的解决方案,你可以用NSAttributedString而不是Core Text创建一个上标/下标效果。我是这样做的:

NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:myString];
// Everything except the first character is rendered with the regular size / position
[str addAttribute:NSFontAttributeName 
     value:font 
     range:NSMakeRange(1, [amountString length]-1)];  // Everything except the first character is rendered with the regular size / position
// First character is 5/8 normal size
[str addAttribute:NSFontAttributeName 
     value:[UIFont fontWithName:initialFont.fontName 
     size:initialFont.pointSize/8*5] 
     range:NSMakeRange(0, 1)];
// Set the baseline offset to push the first character into a superscript position
[str addAttribute:@"NSBaselineOffset" 
     value:[NSNumber numberWithFloat:initialFont.pointSize*1/3] 
     range:NSMakeRange(0, 1)];  

关键行是最后两行,它们使上/下标脚本文本的大小变小,并改变它的垂直位置。值得注意的是,我使用的是字符串(@"NSBaselineOffset"),而不是定义的属性名称常量(NSBaselineOffsetAttributeName)。从我能够收集到的东西来看,我相信NSBaselineOffsetAttributeName是在Mac的库中定义的,但不是为iOS定义的(当我想到这个时,我正在为iOS开发)。因此,我使用了名称字符串本身而不是常量作为属性名。

最新更新