2011-11-30 26 views
6

Tôi đã nghe nói rằng tôi có thể hiển thị một NSAttributedString bằng cách sử dụng CoreText, bất cứ ai có thể nói với tôi như thế nào (Cách đơn giản nhất)?Hiển thị NSAttributedString bằng cách sử dụng CoreText

Vui lòng không trả lời bằng CATextLayer hoặc OHAttributedLabel.

Tôi biết rằng có rất nhiều câu hỏi về vấn đề này trong diễn đàn này, nhưng tôi chưa tìm thấy câu trả lời

Cảm ơn !!

+2

Nếu bạn không muốn sử dụng những giấy gói, có một cái nhìn bên trong, cách họ làm việc. – vikingosegundo

Trả lời

10

Tôi nghĩ rằng cách đơn giản nhất (sử dụng Core Text) là:

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

Sử dụng một Framesetter là hiệu quả hơn nếu bạn đang vẽ rất nhiều văn bản nhưng đây là phương pháp khuyến khích bởi Apple nếu bạn chỉ cần hiển thị một lượng văn bản nhỏ (như nhãn) và không yêu cầu bạn tạo đường dẫn hoặc khung (vì nó được tự động hoàn thành bởi CTLineDraw).

11

Cách đơn giản nhất? Một cái gì đó như thế này:

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

Bắt đầu từ iOS 6 bạn có thể làm như sau:

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

cell.label.attributedText = attributedString ; 
Các vấn đề liên quan