这个问题使我丧命。我不知道出了什么问题。但是以下代码将图像颠倒了。它实际上是垂直翻转的,我不知道为什么。

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();

这将导致:

为什么,为什么呢?

最佳答案

这可能更适合作为评论而不是答案,但是对于评论来说太长了。

正如@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);

关于ios - CGContextRef => CGImageRef => CIImage => CGImageRef => CGContextDrawImage链使图像上下颠倒,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27848194/

10-11 15:40