Skip navigation.
 
mlCustom text via Core Text in a layer.
FROM : John Clayton
DATE : Mon Nov 19 18:39:07 2007

Hi All,

I'm using the following code to draw an attributed string into a layer 
(my own CATextLayer), but the text *always* draws black - is there 
something simple that I'm doing wrong? I am of course assuming that 
the colour into in the attributed string would determine how that 
content is being drawn.

Please note: most code is taken directly from the core-text API docs :-)

// HEADER

@interface TextLayerCustom : EffectorBaseLayer
{
   NSAttributedString* _string;
}

@property(readwrite, retain) NSAttributedString* string;

@end

// IMPL

@implementation TextLayerCustom

- (void) drawInContext:(CGContextRef)context
{
   // core-text, here we come
   
   CGContextSetTextMatrix(context, CGAffineTransformIdentity);
   
   CGMutablePathRef path = CGPathCreateMutable();
   if(path)
   {
       CGPathAddRect(path, NULL, self.bounds);
       
       CTFramesetterRef framesetter = 
CTFramesetterCreateWithAttributedString(
           (CFAttributedStringRef)_string
       );
       
       // Create the frame and draw it into the graphics context
       CTFrameRef frame = CTFramesetterCreateFrame(framesetter,
           CFRangeMake(0, 0), path, NULL);
       
       if(frame)
           CTFrameDraw(frame, context);
       
       if(framesetter)
           CFRelease(framesetter);
       
       if(frame)
           CFRelease(frame);
   }
   
   if(path)
       CFRelease(path);
}

- (id) init
{
   self = [super init];
   _string = 0;
   
   // in order to redraw so that justification and line wrapping take 
effect
   [self setNeedsDisplayOnBoundsChange:YES];
   
   return self;
}

- (void) dealloc
{
   [_string release];
   [super dealloc];
}

- (NSAttributedString*) string
{
   return [[_string retain] autorelease];
}

- (void) setString:(NSAttributedString *)str
{
   [_string release];
   _string = [[NSMutableAttributedString alloc] 
initWithAttributedString:str];
   [self setNeedsDisplay];
}

@end

thanks!!


--
John Clayton
http://www.coderage-software.com/

Related mailsAuthorDate
mlCustom text via Core Text in a layer. John Clayton Nov 19, 18:39
mlRe: Custom text via Core Text in a layer. John Harper Nov 19, 19:45
mlRe: Custom text via Core Text in a layer. John Clayton Nov 19, 19:46
mlRe: Custom text via Core Text in a layer. Aki Inoue Nov 19, 20:03
mlRe: Custom text via Core Text in a layer. John Clayton Nov 19, 23:29
mlRe: Custom text via Core Text in a layer. Aki Inoue Nov 26, 19:04