iosobjective-cuiviewuiimagecgcontextdrawimage

UIImage is reversed when drawn on UIView


I am using camera picker controller to take a picture and I display it in my app. However I am not using UIImageView to display the picture. I am drawing the UIImage on a UIView, and the result I get is the reversed image. Here is the screenshot:

enter image description here

and the result after I click on use photo is:

enter image description here

Here is my code:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

    UIImage *chosenImage = info[UIImagePickerControllerEditedImage];

    dView=[[drawView alloc]initWithFrame:imageUIView.frame];
    [dView drawImage:chosenImage];

    [imageUIView addSubview:dView];

    [picker dismissViewControllerAnimated:YES completion:NULL];

}

and in dView:

-(void)drawImage:(UIImage *) imageToDraw{
    self.pic=imageToDraw;
    [imageToDraw drawInRect:self.frame];
    [self setNeedsDisplay];

}

- (void)drawRect:(CGRect)rect {

CGContextRef context = UIGraphicsGetCurrentContext();

CGRect targetBounds = self.layer.bounds;
    // fit the image, preserving its aspect ratio, into our target bounds
CGRect imageRect = AVMakeRectWithAspectRatioInsideRect(self.pic.size,
                                                           targetBounds);
    // draw the image
CGContextDrawImage(context, imageRect, self.pic.CGImage);

// Save the screen to restore next time around
imageRef = CGBitmapContextCreateImage(context);

}

I tried CGAffineTransformMakeRotation and CGContextRotateCTM to display the image properly, but they rotate the image, instead of making the contents display in correct order. As you can see the contents in the image are totally reversed.

How to draw the uiimage without making any changes to its appearence ?


Solution

  • Your drawView class isn't drawing the image properly. Try this:

    - (void)drawImage:(UIImage *)imageToDraw {
        self.pic = imageToDraw;
        [self setNeedsDisplay];
    }
    
    - (void)drawRect:(CGRect)rect {
        CGRect targetBounds = self.layer.bounds;
            // fit the image, preserving its aspect ratio, into our target bounds
        CGRect imageRect = AVMakeRectWithAspectRatioInsideRect(self.pic.size,
                                                                   targetBounds);
            // draw the image
        [self.pic drawInRect:imageRect];
    }
    
    1. It may be better to add a UIImageView as a subview of your drawView. Let the image view do all the needed work to render the image properly.
    2. Naming conventions. Class names should start will uppercase letters. Variable and method names start with lowercase letters.