iphoneiosuiviewuiimagecontent-model

iOS: UIImage scale to fill inside a UIView


I am subclassing UIView, retrieving a remote image then drawing it to the view using drawRect. This works fine, but the image is then skewed based upon what I set for my views frame.

I can add a contentMode of UIViewContentModeScaleAspectFill to my UIView but it doesn't seem to apply at all to my UIImage that I am drawing, it still squishes the UIImage because it follows the views frame size.

It seems like I should do something like the following, but that just zooms the image 100% within my frame rather than following the contentMode setting:

[image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];

Do I need to do something specific in drawRect: to make my image follow the contentMode property?


Solution

  • I think the simplest solution would be to subclass UIImageView instead of UIView and use the class's contentMode property. Then you don't need to call drawRect, just load the image into the imageView.

    Alternately, if you need to subclass UIView, add a UIImageView to your view, setup springs and struts, set the contentMode, and load up your image.