views:

136

answers:

1

Hi, I'm trying to set up a CTFrame that exactly matches my UITextView's text format in iPad. First of all, I converted UITextView's text to an attributed string. Then I set up a width and a height of drawing box in which Core Text will draw text. I succeeded to draw text using Core Text, but UITextView and Core Text show slightly different results even though I used the same font and size. Specifically, when I used [UIFont systemFontOfSize:21], each space in UITextView has one more pixel than Core Text's result.

It's okay for a short sentence or word, but if UITextView and Core Text have multiple lines, their result become very different. For example, UITextView peforms word-wrapping for one word at the end of line, while Core Text keeps that word in the same line. If you see the attached picture, the start positions of the last word "paragraph" are already very different (8 pixel gap due to 8 space characters).

More badly, if I use different fonts such as a custom font added to my project, each character in UITextView has 1 pixel more.

I'm using Core Text to find the pixel-position of the current cursor in UITextView, so both of them should perfectly match each other, containing the same number of characters and words in each line.

Question: Is there a way to make Core Text object that perfectly matches UITextView's text format?

Thank you!

Here's a code how I set up attributed string. (I just followed Core Text Guide.)

CTFontRef font = CTFontCreateWithName((CFStringRef) [UIFont systemFontOfSize:21.0].fontName, 21.0, NULL);
CFMutableAttributedStringRef attrString2 = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0);
CFAttributedStringReplaceString (attrString2, CFRangeMake(0, 0), (CFStringRef) string);
CFAttributedStringSetAttribute(attrString2, CFRangeMake(0, [string length]),kCTFontAttributeName, font);

-

-

Here's a picture.

alt text

A: 

Answer to myself. I just found very simple solution! Using any font editor, you can just change the width of space character (ascii value 32); an original font for UITextView and a modified font for Core Text or vice versa. I used a freeware font editor FontForge. Though I still have to do some extreme-case tests such as writing Japanese characters and English alphabets in the same line and so on, now it becomes almost possible to find a pixel-position of a cursor/caret in UITextView.

kyu