簡體   English   中英

CGContextRef => CGImageRef => CIImage => CGImageRef => CGContextDrawImage鏈使圖像上下顛倒

[英]CGContextRef => CGImageRef => CIImage => CGImageRef => CGContextDrawImage chain turns image upside down

這個問題使我喪命。 我不知道出了什么問題。 但是以下代碼將圖像顛倒了。 它實際上是垂直翻轉的,我不知道為什么。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM