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

Guy*_*ean 5 iphone cocoa-touch objective-c ios

我已经尝试了几天了.我正在创建一个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;
}
Run Code Online (Sandbox Code Playgroud)

谢谢,盖伊.

Lou*_*nco 6

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

[imageToFlip drawInRect:CGRectMake(0, 0, imageToFlip.size.width, imageToFlip.size.height)];
CGContextScaleCTM(currentContext, -1.0, 1.0);
Run Code Online (Sandbox Code Playgroud)

with(根据评论编辑)

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

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

@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
Run Code Online (Sandbox Code Playgroud)

  • 效果很好!这是基于你的代码的UIImage类:`@implementation UIImage(Flip) - (UIImage*)horizo​​ntalFlip {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` (2认同)