Flip UIImage Along Either Axis

后端 未结 5 1550
余生分开走
余生分开走 2021-01-13 17:05

I\'m trying to create a method which flips a UIImage along the X axis, Y axis, or both. I keep getting close but my transform knowledge isn\'t good enough to get all the way

5条回答
  •  执念已碎
    2021-01-13 17:53

    I finally was able to figure this out. Here is the code that works for anyone else who might need it.

    - (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;
    }
    

提交回复
热议问题