The tutorial only shows how to resize the image (with a constant aspect ratio) to fit within the 52x52 point bounds of the thumbnail (“aspect fit” rules). That leaves white space top+bottom or left+right of the thumbnail, if the original image is not square as well.
The task is to use the “Aspect Fill” rules to make thumbnails that always fill the boundaries of the thumbnail while showing a centered part of the image with the correct aspect ratio.
That requires the following steps in my opinion:
- compare the aspect ratios of the original image as well as the thumbnail
- calculate size and (centered) location of the part of the original image to be resized as the thumbnail
- write the part of the original image determined in 2. to a thumbnail with the correct size.
I have solved steps 1+2 (I think) with the following code:
let horizontalRatio = bounds.width / size.width
let verticalRatio = bounds.height / size.height
let newAspectRatio = bounds.height / bounds.width
if horizontalRatio > verticalRatio {
let tempHeight = size.width * newAspectRatio
let originY = (size.height - tempHeight) / 2
let tempSize = CGSize(width: size.width, height: tempHeight)
} else if horizontalRatio < verticalRatio {
let tempWidth = size.height / newAspectRatio
let originX = (size.width - tempWidth) / 2
let tempSize = CGSize(width: tempWidth, height: size.height)
} else {
// aspect ratio of image and thumbnail are identical --> no cropping needed
}
- I calculate the
horizontalRatio
andverticalRatio
as in the aspect fit example. - I then determine the
newAspectRatio
of the thumbnail to be generated. -
if horizontalRatio > verticalRatio
means that the original image is taller than the thumbnail. - Therefore the part to be cut-out has the original
size.width
and a newtempHeight
that is calculated by applying thenewAspectRatio
to the original width! - The starting point of the cut-out part is at
x=0
andoriginY = (size.height - tempHeight) / 2
I have tested that in the simulator it seems to produce the correct results.
What I haven’t figured out yet is how to crop the original image with the calculated data to the correct aspect ratio of the thumbnail.
Writing the cropped image to the thumbnail size should work as in the aspect fit example.
If anyone has a hint or solution for that I’d be happy to hear that. Improvements to my code above are also always welcome.
I’ll update this post if I find a solution myself.