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
If you're intending to just display the image and not save it, you probably don't want to create a second CGContext. It's far more efficient to just use the already-loaded CGImage in the UIImage, and change the orientation like so:
- (UIImage *)flippedImageByFlippingAlongXAxis:(BOOL)flipOnX andAlongYAxis:(BOOL)flipOnY
{
UIImageOrientation currentOrientation = self.imageOrientation;
UIImageOrientation newOrientation = currentOrientation;
if (flipOnX == YES) {
switch (newOrientation) {
case UIImageOrientationUp:
newOrientation = UIImageOrientationUpMirrored;
break;
case UIImageOrientationDown:
newOrientation = UIImageOrientationMirrored;
break;
case UIImageOrientationUpMirrored:
newOrientation = UIImageOrientationUp;
break;
case UIImageOrientationDownMirrored:
newOrientation = UIImageOrientationDown;
break;
case UIImageOrientationLeft:
newOrientation = UIImageOrientationLeftMirrored;
break;
case UIImageOrientationRight:
newOrientation = UIImageOrientationRightMirrored;
break;
case UIImageOrientationLeftMirrored:
newOrientation = UIImageOrientationLeft;
break;
case UIImageOrientationRightMirrored:
newOrientation = UIImageOrientationRight;
break;
}
}
if (flipOnY == YES) {
switch (newOrientation) {
case UIImageOrientationUp:
newOrientation = UIImageOrientationDownMirrored;
break;
case UIImageOrientationDown:
newOrientation = UIImageOrientationUpMirrored;
break;
case UIImageOrientationUpMirrored:
newOrientation = UIImageOrientationDown;
break;
case UIImageOrientationDownMirrored:
newOrientation = UIImageOrientationUp;
break;
case UIImageOrientationLeft:
newOrientation = UIImageOrientationRightMirrored;
break;
case UIImageOrientationRight:
newOrientation = UIImageOrientationLeftMirrored;
break;
case UIImageOrientationLeftMirrored:
newOrientation = UIImageOrientationRight;
break;
case UIImageOrientationRightMirrored:
newOrientation = UIImageOrientationLeft;
break;
}
}
return [UIImage imageWithCGImage:self.CGImage scale:self.scale orientation:newOrientation];
}
When you start a new CGContext and doing flip using CGContextDrawImage, you're allocating another block of memory to hold the same bytes in a different order. By changing the UIImage orientation, you're able to avoid another allocation. The same image data is used, just drawn in a different orientation.