iPhone:使用Quartz 2D转换图像

1 iphone core-graphics quartz-graphics cgcontext

我试图使用CGContextRef对图像应用一些转换.我正在使用CGContextTranslateCTM,CGContextScaleCTM和CGContextRotateCTM函数,但为了保持简单,我们只关注第一个.我想知道为什么下面的代码会产生完全原始的图像?!我错过了什么吗?

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

CGContextRef g = CGBitmapContextCreate((void*) pixelData, 
                                                       width, 
                                                       height, 
                                                       RGBA_8_BIT, 
                                                       bytesPerRow, 
                                                       colorSpace, 

                                                   kCGImageAlphaPremultipliedLast);

CGContextSetShouldAntialias(g, YES);

CGContextSetInterpolationQuality(g, kCGInterpolationHigh);

CGContextTranslateCTM( g,translateX, translateY );


CGImageRef tempImg  = CGBitmapContextCreateImage (g);
CGContextDrawImage( g, CGRectMake (0, 0, width, height), tempImg );
CGContextRelease(g);
CGColorSpaceRelease( colorSpace );
Run Code Online (Sandbox Code Playgroud)

此外,翻译后,如何在这一个上绘制另一个图像,但具有部分透明度(例如alpha = 0.5).

我搜索了很多,但没有找到答案,任何帮助表示赞赏...... :)

请注意,我正在从pixelData创建上下文,并且在翻译后创建tempImg.初始化没有任何问题,因为原始图像当前正在生成,但问题在于我想要的翻译.

Ben*_*tow 5

对图形状态的转换仅影响后续绘图操作 - 它们不会更改现有图像数据.如果要将变换应​​用于图像,请尝试以下操作:

  1. 创建一个空的CGContext(在iPhone上,使用UIGraphicsBeginImageContext)
  2. 翻译,缩放或旋转图形状态
  3. 将现有图像绘制到其中.
  4. 从新的CGContext获取图像(在iPhone上,使用UIGraphicsGetImageFromCurrentImageContext)

执行步骤3时,现有图像将被应用到转换中,并将其绘制到新的图形上下文中.这里的诀窍是,为了应用转换,我们必须实际绘制一些东西.

你可以用这种方式做一些非常酷的转换.您可以绘制一半图像,应用一些变换,然后绘制更多图像.