2011-11-30 6 views
6

CoreTextを使用してNSAttributedStringを表示できると聞いたことがあります。CoreTextを使用してNSAttributedStringを表示します。

CATextLayerまたはOHAttributedLabelで回答しないでください。

私はこのフォーラムではこのことについて多くの質問があることを知っているが、私は答えに

感謝を見つけることがあります!

+2

あなたがそれらのラッパーを使用しない場合、彼らはどのように動作するか、内部を見てみましょう。 – vikingosegundo

答えて

10

私は(コア・テキストを使用して)最も簡単な方法だと思う:あなたが大量のテキストを描画している場合

Framesetterを使用して
// Create the CTLine with the attributed string 
CTLineRef line = CTLineCreateWithAttributedString(attrString); 

// Set text position and draw the line into the graphics context called context 
CGContextSetTextPosition(context, x, y); 
CTLineDraw(line, context); 

// Clean up 
CFRelease(line); 

は、より効率的であるが、これは推奨される方法です(ラベルのように)少量のテキストを表示するだけで、パスやフレームを作成する必要はありません(これは自動的にCTLineDrawで行われます)。 IOSから始まっ

11

最も簡単な方法は?このような何か:

CGContextRef context = UIGraphicsGetCurrentContext(); 

// Flip the coordinate system 
CGContextSetTextMatrix(context, CGAffineTransformIdentity); 
CGContextTranslateCTM(context, 0, self.bounds.size.height); 
CGContextScaleCTM(context, 1.0, -1.0); 

// Create a path to render text in 
CGMutablePathRef path = CGPathCreateMutable(); 
CGPathAddRect(path, NULL, self.bounds); 

// An attributed string containing the text to render 
NSAttributedString* attString = [[NSAttributedString alloc] 
            initWithString:...]; 

// create the framesetter and render text 
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attString); 
CTFrameRef frame = CTFramesetterCreateFrame(framesetter, 
         CFRangeMake(0, [attString length]), path, NULL); 

CTFrameDraw(frame, context); 

// Clean up 
CFRelease(frame); 
CFRelease(path); 
CFRelease(framesetter); 
1

では、次の操作を行うことができます6:

NSMutableParagraphStyle *paragrahStyle = [[NSMutableParagraphStyle alloc] init]; 
[paragrahStyle setLineSpacing:40]; 
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragrahStyle range:NSMakeRange(0, [labelText length])]; 

cell.label.attributedText = attributedString ; 
関連する問題