Display the specified area of an image in UIImageView

Recently, I have an UI optimization that is prioritizing to display the top area of an image rather than the center in an image view. Usually, we set .scaleAspectFill to the contentMode of the image view to display a poster image, but the image view will clip both ends of the image and save the center by default. Other options of the contentMode are also useless, the top mode will correctly display the top area of the image, but the image view will not scale the image. I searched this question by Google and found several solutions.

The first plan is to create two views, one is the container and the other is the image view used to display posters. Make the aspect of the image view is always equal to the image’s, set its leading, trailing and top constraints equal to the container view and set the clipsToBounds of the container view to true, finally, the rendering effect of them is what we want. This way is no problem but too complex to a small optimization.

Another solution is to clip the image to a proper size. Clipping images can solve many problems, do we have any other methods? Finally, I find a property contentsRect of CALayer, it can control the rendering area of its content. The type of the contentsRect is CGRect, the x and y refer to the rendering origin, the value range is from 0 to 1. The width and height refer to the rendering size, the value range is also from 0 to 1. Such as, setting the contentsRect to CGRect(x: 0, y: 0, width: 1, height: 1) will display the top half part of the content in the layer. In the end, I choose this way to fill my requirements. Actually, I completely don’t know this property of CALayer previously.