Superscript, Subscript text with Core Text iPhone

只愿长相守 提交于 2019-12-13 18:11:37

问题


Can anyone explain me, How to draw superscript and subscript alphabets with Core Text?

Thanks.


回答1:


I noticed that this question is a bit old, I hope you still require assistance in this matter and that this post will help you.

you can use NSAttributedString (or its mutable counterpart NSMutableAttributedString) to assign different attributes (such as font, both name and size) to specific ranges of a single string.

Superscript and subscript are not natively supported by core text and to make them look good you might need to do quite a lot of work. Fortunately there is an open source project developed by Oliver Drobnik from cocoa genetics that allows you to easily convert HTML into NSAttributedString (or NSMutableAttributedString), feed it into a custom textview and show superscripts and subscripts (along with many other HTML and CSS) as they would appear in a UIWebview, but without the need to use a UIWebview. You can download the project from here.

While a lot of effort has been put into this project, there are two caveats:

  1. The computations can be at times very performance intensive.
  2. Not all HTML tags and CSS features are supported yet.



回答2:


IF NSAttributedString is an acceptable solution you can create a superscript / subscript effect with NSAttributedString rather than Core Text. This is how I did it:

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)];  

The key lines are the last two, which make the size of the super/sub script text smaller and change it's vertical position. It's worth noting that I'm using a string (@"NSBaselineOffset") instead of a defined attribute name constant (NSBaselineOffsetAttributeName). From what I was able to gather I believe that NSBaselineOffsetAttributeName is defined in the libraries for Mac but not for iOS (which I was developing for when I came up with this). As I result I used the name string itself rather than a constant for the attribute name.



来源:https://stackoverflow.com/questions/6786570/superscript-subscript-text-with-core-text-iphone

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!