Ser Pounce
Ser Pounce

Reputation: 14527

How to move CGMutablePathRef?

I have a snippet of code below that draws a string to a UIView using CoreText:

- (void) drawRect:(CGRect)rect
{
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)self.text);
    CGMutablePathRef mutablePathRef = CGPathCreateMutable();
    CGPathAddRect(mutablePathRef, NULL, self.bounds);
    CTFrameRef frameRef = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), mutablePathRef, NULL);

    CGFloat frameHeight = [self calculateHeightForFrame: frameRef];

    //what do I do here to resposition the mutablePathRef?

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetTextMatrix(context, CGAffineTransformIdentity);
    CGContextTranslateCTM(context, 0, self.bounds.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    CTFrameDraw(frameRef, context); 

    CFRelease(frameRef);
    CGPathRelease(mutablePathRef);
    CFRelease(framesetter);
}

I initialize a frame and frame setter, and attach them to a CGMutablePath. Then I use the CTLine origins from the frame to calculate the height of the text so I can center it vertically.

After this point I'm a little stumped. Is there a way to move the position of the CGMutablePath to a new origin so it will be centered vertically? I tried CGPathMoveToPoint and it didn't work.

Or do I need to create a brand new CGMutablePath and a brand new frame and frame setter? If so, how do I remove the CGMutablePath? Will it be removed if I release it?

Any hints on an efficient way I could solve this would be great, thanks.

Upvotes: 0

Views: 846

Answers (2)

lnafziger
lnafziger

Reputation: 25740

This question shows how to vertically center text with Core Text.

Basically, you need to determine the height of the text and modify your path before you call CGPathAddRect().

Upvotes: 0

Nicolas Bachschmidt
Nicolas Bachschmidt

Reputation: 6505

Once your CGMutablePathRef has been used to create the frame, modifying the path has not effect on the frame. Moreover CGPathMoveToPoint doesn't move the path itself but is current point, allowing the append new subpaths.

You can change the position of the text by applying a translation on the context before drawing.

CGContextTranslateCTM(x, y);

Upvotes: 1

Related Questions