My current method of combining UIImages come from this answer on SO, as well as this popular question on resizing UIImage with aspect ratio. My current issue is the following:
I have an UIImage called pictureImage
taken with the camera that comes out to the standard dimension 2448*3264
. I also have a UIImageView called self.annotateView
that has a frame of 320*568
where the user could draw and annotate the picture. When I present the pictureImage
in a UIImageView
, I set the image presentation as Aspect Fill so that it takes up the whole iPhone screen. Of course this means parts of pictureImage
is cut off on both left and right (in fact 304 pixels on both sides), but this intended.
My problem is, when I combine the UIImages pictureImage
and annotateView.image
to a new dimension of 320*568
, my combined image alters the original aspects of annotateView.image
by stretching it horizontally. This is strange since the new dimensions are exactly that of annotateView.image
's original dimensions.
Here is what the outcome looks like -
Before combining the UIImages
After combining the images
Note that the underlying picture is not stretched. However, annotateView.image
is stretched only horizontally, not vertically.
Here is my code for merging the UIImages.
//Note: self.firstTakenImage is set to 320*568
CGSize newSize = CGSizeMake(self.firstTakenImage.frame.size.width, self.firstTakenImage.frame.size.height);
UIGraphicsBeginImageContext(newSize);
[self.firstTakenImage.image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
[self.drawView.image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *combinedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
While doing the drawInRect, you have to redo the scaling and centering that the system did for you with AspectFill to make it match the original process. Something like this:
When you call
[self.drawView.image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
you need to modify the frame to account for the difference in aspect ratio that you described (because you are chopping some of the image off on both sides).That means modifying the
x
position and thewidth
that you are drawing the annotation image.The modification is based on the difference between the 2 rects when scaled to the same height. You say this is
304
, so you can initially setx
to 304 and thewidth
tonewSize.width - 608
to test. But really the difference should be calculated...Mackworth's answer in Swift 3.x