我尝试翻转(镜像)UIImage的方式有什么问题?

时间:2012-04-23 14:35:19

标签: iphone objective-c ios cocoa-touch

我已经尝试了几天了。我正在创建一个sprite表加载器,但是我也必须能够加载面向相反方向的sprite。这涉及翻转我已加载的图像。

我已经尝试使用UIImageOrientation / UIImageOrientationUpMirrored方法执行此操作,但这绝对没有效果,只需绘制与之前完全相同的方向框架。

此后我尝试了一种稍微复杂的方式,我将在下面介绍。但仍然只是以与加载到应用程序中完全相同的方式绘制图像。 (没有镜像)。

我已经包含了下面的方法(以及我的评论,以便你可以按照我的思维模式),你能看到我做错了吗?

- (UIImage*) getFlippedFrame:(UIImage*) imageToFlip
{
//create a context to draw that shizz into
UIGraphicsBeginImageContext(imageToFlip.size);
CGContextRef currentContext = UIGraphicsGetCurrentContext();



//WHERE YOU LEFT OFF. you're attempting to find a way to flip the image in imagetoflip. and return it as a new UIimage. But no luck so far.
[imageToFlip drawInRect:CGRectMake(0, 0, imageToFlip.size.width, imageToFlip.size.height)];

//take the current context with the old frame drawn in and flip it.
CGContextScaleCTM(currentContext, -1.0, 1.0);

//create a UIImage made from the flipped context. However will the transformation survive the transition to UIImage? UPDATE: Apparently not.

UIImage* flippedFrame = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return flippedFrame;
}

谢谢你, 盖

1 个答案:

答案 0 :(得分:6)

我原本以为你必须改变上下文的变换然后画出来。此外,您需要翻译,因为您正在翻转到负坐标,因此,请替换

[imageToFlip drawInRect:CGRectMake(0, 0, imageToFlip.size.width, imageToFlip.size.height)];
CGContextScaleCTM(currentContext, -1.0, 1.0);

with(根据评论编辑)

CGContextTranslateCTM(currentContext, imageToFlip.size.width, 0);      
CGContextScaleCTM(currentContext, -1.0, 1.0);
[imageToFlip drawInRect:CGRectMake(0, 0, imageToFlip.size.width, imageToFlip.size.height)];

注意:来自评论,要使用的类别

@implementation UIImage (Flip) 
  - (UIImage*)horizontalFlip { 
     UIGraphicsBeginImageContext(self.size); 
     CGContextRef current_context = UIGraphicsGetCurrentContext();                           
     CGContextTranslateCTM(current_context, self.size.width, 0);
     CGContextScaleCTM(current_context, -1.0, 1.0); 
     [self drawInRect:CGRectMake(0, 0, self.size.width, self.size.height)]; 
     UIImage *flipped_img = UIGraphicsGetImageFromCurrentImageContext(); 
     UIGraphicsEndImageContext(); 
     return flipped_img; 
  } 
@end