Paresh Masani
Paresh Masani

Reputation: 7504

iOS: Mixing Core Graphics draw path and UIKit draw text functions

I am using following context in UIView's extended class's drawrect method to draw Paths and Strings.

CGContextRef context = UIGraphicsGetCurrentContext();

CGContextScaleCTM(context, 1, -1);
CGContextTranslateCTM(context, 0, -rect.size.height);

To Draw Path I use

CGContextSetRGBStrokeColor(context, 0, 0, 0, 1.0f);
CGContextSetLineWidth(context, 1);
CGContextBeginPath(context);
CGContextMoveToPoint(context, origin.x, origin.y);
CGContextAddLineToPoint(context, currentX, origin.y);
......
CGContextStrokePath(context);

To Draw text I use

CGContextSetLineWidth(context, 2.0);    
[self.title drawInRect:CGRectMake(100, 100, 200, 40) withFont:font];

I get paths correctly but Text gets up side down! If I remove CGContextScaleCTM and CGContextTranslateCTM I get path up side down! Can someone help me to resolve this please.

Upvotes: 1

Views: 1624

Answers (2)

Paresh Masani
Paresh Masani

Reputation: 7504

I end up writting following code. May help someone!

- (void)drawText:(NSString*)text context:(CGContextRef)context rect:(CGRect)rect verticle:(BOOL)verticle {
    CGAffineTransform translate = CGAffineTransformMakeTranslation(0, -rect.size.height);
    CGAffineTransform transform = translate;

    if(verticle) {
        CGAffineTransform rotation = CGAffineTransformMakeRotation(M_PI/2);
        transform = CGAffineTransformConcat(translate, rotation);
    }

    CGContextSetTextMatrix(context, transform);
    CGContextShowTextAtPoint(context, rect.origin.x, rect.origin.y, [text UTF8String], text.length);

}

Upvotes: 1

stevekohls
stevekohls

Reputation: 2255

Save your previous context before drawing your path and restore it afterward:

CGContextRef context = UIGraphicsGetCurrentContext();

// save the original context
CGContextSaveGState(context);

CGContextScaleCTM(context, 1, -1);
CGContextTranslateCTM(context, 0, -rect.size.height);

// draw path

// restore the context
CGContextRestoreGState();

// draw text

That should do it.

Upvotes: 2

Related Questions