翻转上下文中的CGBitmapContextCreateImage

时间:2013-08-16 06:06:01

标签: iphone ios objective-c image cgcontext

我有一个背景,我已经完成了一些绘图。现在我想保存一个结果。因为倒置的上下文y轴首先我要翻转所有内容,然后创建图像:

// 1. Flip Y
CGContextTranslateCTM(context, 0, height);
CGContextScaleCTM(context, 1.0, -1.0);

// 2. Create image
CGImageRef rawMask = CGBitmapContextCreateImage(context);

但是图像没有翻转。即使我用2改变动作顺序1,图像仍然没有翻转。我无法理解为什么以及如何解决它。更重要的是'为什么',因为在我的逻辑中,如果我用颠倒的绘图翻转上下文,那应该没问题。

2 个答案:

答案 0 :(得分:2)

CTM会影响您在设置CTM后执行的绘图操作。也就是说,更改CTM可以更改后续绘图操作修改的像素。

CTM不会直接影响CGBitmapContextCreateImageCGBitmapContextCreateImage只是将上下文中的像素复制到图像中。它根本不看CTM。

因此,您从问题中省略了程序的关键部分:实际修改像素的部分。正确的顺序是:

// 1. Flip Y axis.
CGContextTranslateCTM(context, 0, height);
CGContextScaleCTM(context, 1.0, -1.0);

// 2. Draw into context.  For example:
CGContextBeginPath(context);
CGContextAddEllipseInRect(context, someRect);
CGContextSetFillColorWithColor(context, ...);
CGContextFillPath(context);

// 3. Create image.
CGImageRef rawMask = CGBitmapContextCreateImage(context);

答案 1 :(得分:0)

CGContextRef context = UIGraphicsGetCurrentContext(); //Check if this is valid

CGContextTranslateCTM(context, 0, height);
CGContextScaleCTM(context, 1.0, -1.0);

CGImageRef rawMask = CGBitmapContextCreateImage(context);
UIImage* img = [UIImage imageWithCGImage:rawMask];
CGImageRelease(imgRef);

如果UIGraphicsGetCurrenContext();无效,则:

如果你只想要一个图像:使用UIGraphicsBeginImageContext()创建一个上下文,然后用UIGraphicsGetImageFromCurrentImageContext()提取一个UIImage(不需要中间的CGImage),然后用UIGraphicsEndImageContext()来清理。