Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>[EDIT - this code is a bit moldy being from 2011 and all but I incorporated @ArtOfWarefare's mods]</p> <p>You can't do this w/ UIImageView. I created a simple UIView subclass <code>MyImageView</code> that contains a UIImageView. Code below.</p> <pre><code>// MyImageView.h #import &lt;UIKit/UIKit.h&gt; @interface MyImageView : UIView { UIImageView *_imageView; } @property (nonatomic, assign) UIImage *image; @end </code></pre> <p>and</p> <pre><code>// MyImageView.m #import "MyImageView.h" @implementation MyImageView @dynamic image; - (id)initWithCoder:(NSCoder*)coder { self = [super initWithCoder:coder]; if (self) { self.clipsToBounds = YES; _imageView = [[UIImageView alloc] initWithFrame:self.bounds]; _imageView.contentMode = UIViewContentModeScaleAspectFill; [self addSubview:_imageView]; } return self; } - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.clipsToBounds = YES; _imageView = [[UIImageView alloc] initWithFrame:self.bounds]; _imageView.contentMode = UIViewContentModeScaleAspectFill; [self addSubview:_imageView]; } return self; } - (id)initWithImage:(UIImage *)anImage { self = [self initWithFrame:CGRectZero]; if (self) { _imageView.image = anImage; [_imageView sizeToFit]; // initialize frame to be same size as imageView self.frame = _imageView.bounds; } return self; } // Delete this function if you're using ARC - (void)dealloc { [_imageView release]; [super dealloc]; } - (UIImage *)image { return _imageView.image; } - (void)setImage:(UIImage *)anImage { _imageView.image = anImage; [self setNeedsLayout]; } - (void)layoutSubviews { if (!self.image) return; // compute scale factor for imageView CGFloat widthScaleFactor = CGRectGetWidth(self.bounds) / self.image.size.width; CGFloat heightScaleFactor = CGRectGetHeight(self.bounds) / self.image.size.height; CGFloat imageViewXOrigin = 0; CGFloat imageViewYOrigin = 0; CGFloat imageViewWidth; CGFloat imageViewHeight; // if image is narrow and tall, scale to width and align vertically to the top if (widthScaleFactor &gt; heightScaleFactor) { imageViewWidth = self.image.size.width * widthScaleFactor; imageViewHeight = self.image.size.height * widthScaleFactor; } // else if image is wide and short, scale to height and align horizontally centered else { imageViewWidth = self.image.size.width * heightScaleFactor; imageViewHeight = self.image.size.height * heightScaleFactor; imageViewXOrigin = - (imageViewWidth - CGRectGetWidth(self.bounds))/2; } _imageView.frame = CGRectMake(imageViewXOrigin, imageViewYOrigin, imageViewWidth, imageViewHeight); } - (void)setFrame:(CGRect)frame { [super setFrame:frame]; [self setNeedsLayout]; } @end </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload