3
votes

I load a image and create a mirror in this way:

 originalImg = [UIImage imageNamed:@"ms06.png"];
 mirrorImg = [UIImage imageWithCGImage:[originalImg CGImage] scale:1.0 orientation:UIImageOrientationUpMirrored];

Then I set the above UIImage object to a subclass of UIView, and override the drawRect:

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);

    CGAffineTransform t0 = CGContextGetCTM(context);
    CGContextConcatCTM(context, t0);

    CGContextDrawImage(context, self.bounds, [image CGImage]);
    CGContextRestoreGState(context);
}

No matter which image I draw, the displayed image always be the original one, mirrored image was never displayed when set to the UIView subclass. I'm sure that the mirrored image was set to the UIView correctly because the debug info showed that the orientation member variable equals to 4, which means "UIImageOrientationUpMirrored", while the original image equals to 0. Does anyone could help me with this problem, thanks.

I also tried to display the mirrored image in UIImageView with setImage: and it works correctly. By the way I found that the breakpoint in drawRect was never hit when call the setImage of UIImageView, how can we define the drawing behavior(such as draw a line above the image) when loading image to the UIImageView?

1
Try changing your code with, [UIImage imageWithCGImage:[originalImg CGImage] scale:1.0 orientation:UIImageOrientationRightMirrored]; OR [UIImage imageWithCGImage:[originalImg CGImage] scale:1.0 orientation:UIImageOrientationLeft];Dhruv
Thanks for you response but neither of them works.Hanming WU
If you just need mirrored image,your initial code is enough,why do you want to use drawrect method?Dhruv
Because I want to draw mirrored image in an UIView, not in UIImageView.Hanming WU

1 Answers

1
votes

You mirrow the image on UI-Level. This returns a new UIImage, but the CGImage stays the same. If you do some NSLogs, you will notice this.

You can also do transformations on UI-Level. If you use this approach, I would suggest to use originalImg.scale instead of 1.0. Then the code would work for retina and non-retina displays.

[UIImage imageWithCGImage:[originalImg CGImage] scale:originalImg.scale orientation:UIImageOrientationUpMirrored];

If you really need to mirror the CGImage, take a look at NYXImagesKit on GitHub (see UIImage+Rotating.m)