开发者

Superscript, Subscript text with Core Text iPhone

Can anyone explain me, How to draw superscript and subscript alphabets w开发者_如何转开发ith Core Text?

Thanks.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜