Oliver
Oliver

Reputation: 23510

iPhone - Image drawn upside down into a CGGraphic context (custom UIView)

I have a custom view with that code :

- (void)drawRect:(CGRect)rect
{
    UIImage* theImage = [UIImage imageNamed:@"blue_arrow"];

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
    CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
    CGContextSetLineWidth(context, 1.0);
    CGContextSetTextDrawingMode(context, kCGTextFill);

    CGPoint posOnScreen = self.center;
    CGContextDrawImage(context, CGRectMake(posOnScreen.x - theImage.size.width/2, 
                                           posOnScreen.y - theImage.size.height/2,                             
                                           theImage.size.width, 
                                           theImage.size.height), 
                       theImage .CGImage);
}

The image is an arrow, pointiing to the top.

But when drawn, it is draw upside down, pointing to bottom.

What causes that problem ?
How may I correct that, naturally without side effect ?

Upvotes: 0

Views: 4625

Answers (1)

Pontus Granström
Pontus Granström

Reputation: 1089

This is because Core Graphics is using a flipped coordinate system.

You could try flipping the object you're drawing to using the isFlipped property.

Or you could try using this code in your drawing method (Source):

CGContextTranslateCTM(context, 0, image.size.height);
CGContextScaleCTM(context, 1.0, -1.0);

Upvotes: 2

Related Questions