iosobjective-cuiimageviewuiimageuiviewcontentmode

Change how UIViewContentModeScaleAspectFill works


At the moment this setting (on a UIImageView for instance) will keep the centre of the UIImage in the centre of the UIImageView and "crop" the edges that exceed the bounds equally on both sides.

Is there a way to change this at all?

For instance, if I wanted it to keep the top edge of the UIImage in line with the top edge of the UIImageView and just crop off the bottom when scaled etc...


Solution

  • One approach is to keep using UIImageView's automatic scaling (UIViewContentModeScaleAspectFit or UIViewContentModeScaleAspectFill, so that the aspect stays right), and then lop off the parts you don't want by applying a layer mask.

    Alternatively (this is what I would do), just draw the image with the desired cropping, yourself.

    For example, set the image as the contents of a layer and then set the layer's contentsRect (this determines what region of the image is displayed as the layer's contents) and contentsGravity (this determines how the image is pinned / scaled to the layer's bounds). You can change those values in real time (and it is even animated).

    Or, when you want a cropped version, just whip out a new image graphics context, draw the image into it repositioned so that the right area overlaps the context in the right way, pull out the result image, and display it.