iphone - 沿任一轴翻转 UIImage

标签 iphone cocoa-touch core-graphics

我正在尝试创建一个沿 X 轴、Y 轴或两者翻转 UIImage 的方法。我一直在接近,但我的变换知识还不够好,无法一路到达那里。这是我到目前为止的代码:

- (UIImage *)flippedImageByAxis:(MVImageFlip)axis{
     UIGraphicsBeginImageContext(self.size);
     CGContextRef context = UIGraphicsGetCurrentContext();
     CGAffineTransform verticalFlip = CGAffineTransformMake(1, 0, 0, -1, 0, self.size.height);
     CGAffineTransform horizFlip = CGAffineTransformMake(-1.0, 0.0, 0.0, 1.0, self.size.width, 0.0);

     if(axis == MVImageFlipXAxis || axis == MVImageFlipXAxisAndYAxis)
         CGContextConcatCTM(context, horizFlip);
     if(axis == MVImageFlipYAxis || axis == MVImageFlipXAxisAndYAxis)
         CGContextConcatCTM(context, verticalFlip);

     CGContextDrawImage(context, CGRectMake(0.0, 0.0, self.size.width, self.size.height), [self CGImage]);

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

     return flipedImage;
 }

这会翻转图像,但不正确。 Y 翻转图像根本不会翻转,X 翻转图像看起来像 XY 图像应该看起来像的样子,而 XY 图像看起来像 Y 图像应该看起来像的样子。组合这些变换并让它们正常工作让我很头疼。

MVImageFlip 枚举就是您在代码中看到的三个枚举。没什么特别的。

最佳答案

我终于明白了这一点。以下代码适用于其他可能需要它的人。

- (UIImage *)flippedImageByAxis:(MVImageFlip)axis{
    UIGraphicsBeginImageContext(self.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    if(axis == MVImageFlipXAxis){
        // Do nothing, X is flipped normally in a Core Graphics Context
    } else if(axis == MVImageFlipYAxis){
        // fix X axis
        CGContextTranslateCTM(context, 0, self.size.height);
        CGContextScaleCTM(context, 1.0f, -1.0f);

        // then flip Y axis
        CGContextTranslateCTM(context, self.size.width, 0);
        CGContextScaleCTM(context, -1.0f, 1.0f);
    } else if(axis == MVImageFlipXAxisAndYAxis){
        // just flip Y
        CGContextTranslateCTM(context, self.size.width, 0);
        CGContextScaleCTM(context, -1.0f, 1.0f);
    }

    CGContextDrawImage(context, CGRectMake(0.0, 0.0, self.size.width, self.size.height), [self CGImage]);

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

    return flipedImage;
}

关于iphone - 沿任一轴翻转 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6462070/

相关文章:

ios - 在第二个 View Controller 中使用 GameScene 的分数

iphone - 在上一个终点和下一个起点之间画一条线

swift3 - 需要支持 Apple Pencil/Finger 在 Swift 3 上绘图

iphone - 手动使用 CoreGraphics 绘制阴影?

iphone - Cocos2D iPhone - 屏幕坐标 x Sprite 的内部坐标

iphone - UIScrollView 在 iOS 4.0 上缩放时不调用 layoutSubviews

IOS-如何将视频添加为 ViewController 背景并使用 swift 在运行时添加约束

objective-c - 如何在选择器方法中发送两个参数?

ios - 长按 UITextView 后添加 "Select All"选项

ios - 另一个“NSInvalidArgumentException:无法识别的选择器发送到实例”帖子