这个问题让我感到害怕。我不知道出了什么问题。但是下面的代码将图像颠倒了。它实际上是垂直翻转,我不知道为什么。
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();
这将导致:
为什么,为什么?
答案 0 :(得分:2)
这个可能更适合作为评论而非答案,但评论时间太长了。
正如@Andrea所说,你创建CGContext和CIContext有点奇怪。如果您只想从CGImageRef中提取UIImage,可以使用
UIImage *newImage = [[UIImage alloc] initWithCGImage:cgImg]
生成的newImage
仍会被翻转。 UIImages和CGContextRefs使用的坐标系具有相反方向的垂直轴。我建议你在绘图时垂直翻转你的初始CGContextRef:
CGContextSaveGState(context);
CGContextTranslateCTM(context, 0, CGBitmapContextGetHeight(context));
CGContextScaleCTM(context, 1, -1);
// All your drawing code goes here.
CGContextRestoreGState(context);