Reputation: 1095
This issue kills me. I do not know what is going wrong. But the following code turns the image upside down. It does a vertical flip in fact and I do not know why.
UIFont *font = [UIFont fontWithName:fontName size:fontSize];
NSMutableDictionary *attributes = [[NSMutableDictionary alloc] init];
[attributes setObject:font forKey:NSFontAttributeName];
[attributes setObject:[NSNumber numberWithFloat:kStrokeWidth] forKey:NSStrokeWidthAttributeName];
[attributes setObject:[UIColor redColor] forKey:NSStrokeColorAttributeName];
[attributes setObject:style forKey:NSParagraphStyleAttributeName];
[text drawInRect:drawRect withAttributes:attributes];
[attributes removeObjectForKey:NSStrokeWidthAttributeName];
[attributes removeObjectForKey:NSStrokeColorAttributeName];
[attributes setObject:[UIColor blueColor] forKey:NSForegroundColorAttributeName];
[text drawInRect:drawRect withAttributes:attributes];
CGImageRef cgImg = CGBitmapContextCreateImage(context);
CIImage *beginImage = [CIImage imageWithCGImage:cgImg];
CIContext *cicontext = [CIContext contextWithOptions:nil];
CGImageRef cgimg = [cicontext createCGImage:beginImage fromRect:[beginImage extent]];
CGContextDrawImage(context, [beginImage extent] , cgimg);
CGImageRelease(cgImg);
CGImageRelease(cgimg);
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
This will result in this:
Why, oh why?
Upvotes: 1
Views: 1528
Reputation: 7102
This might be more appropriate as a comment than as an answer, but it's too long for a comment.
As @Andrea noted, it's a little weird that you are creating both a CGContext and CIContext. If you just want to extract a UIImage from a CGImageRef you can use
UIImage *newImage = [[UIImage alloc] initWithCGImage:cgImg]
The resulting newImage
will still be flipped. The coordinate systems used by UIImages and CGContextRefs have oppositely oriented vertical axes. I recommend that you flip your initial CGContextRef vertically while drawing:
CGContextSaveGState(context);
CGContextTranslateCTM(context, 0, CGBitmapContextGetHeight(context));
CGContextScaleCTM(context, 1, -1);
// All your drawing code goes here.
CGContextRestoreGState(context);
Upvotes: 2