一:在绘制到context前通过矩阵垂直翻转坐标系
// uiImage是将要绘制的UIImage图片,width和height是它的宽高
CGContextTranslateCTM(context, 0, height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), uiImage.CGImage);
二:使用UIImage的drawInRect函数,该函数内部能自动处理图片的正确方向
// uiImage是将要绘制的UIImage图片,width和height是它的宽高
UIGraphicsPushContext( context );
[uiImage drawInRect:CGRectMake(0, 0, width, height)];
UIGraphicsPopContext();
三:垂直翻转投影矩阵
这种方法通过设置上下颠倒的投影矩阵,使得原本y轴向上的GL坐标系看起来变成了y轴向下,并且坐标原点从屏幕左下角移到了屏幕左上角。如果你习惯使用y轴向下的坐标系进行二维操作,可以使用这种方法,同时原本颠倒的图片经过再次颠倒后回到了正确的方向:
[cpp] view plaincopy
// uiImage是将要绘制的UIImage图片,width和height是它的宽高
// 图片被颠倒的绘制到context
CGContextDrawImage(context, CGRectMake(0, 0, width, height), uiImage.CGImage);
// 设置上下颠倒的投影矩阵(则原来颠倒的图片回到了正确的方向)
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrthof( 0, framebufferWidth, framebufferHeight, 0, -1, 1 );
===================================================
这些方法绘制出来的图片不会出现反转的情况。
/////////////////////////////////////////////////////////////////////////////
四、这种绘制的图片会发生反转
NSString *path = [[NSBundle mainBundle] pathForResource:@"dog" ofType:@"png"];
UIImage *img = [UIImage imageWithContentsOfFile:path];
CGImageRef image = img.CGImage;
CGContextSaveGState(context);
CGRect touchRect = CGRectMake(0, 0, img.size.width, img.size.height);
CGContextDrawImage(context, touchRect, image);
CGContextRestoreGState(context);
iOS 绘制UIImage的方式
猜你喜欢
转载自dreamahui.iteye.com/blog/1842950
今日推荐
周排行