-
Notifications
You must be signed in to change notification settings - Fork 1
AA 1.22. Displaying Images with UIImageView
Use the UIImageView class.
Let’s start with our view controller’s implementation file:
#import "ViewController.h" @interface ViewController () @property (nonatomic, strong) UIImageView *myImageView; @end
Go ahead and instantiate the image view and place the image in it:
- (void)viewDidLoad { [super viewDidLoad]; UIImage *macBookAir = [UIImage imageNamed:@"MacBookAir"]; self.myImageView = [[UIImageView alloc] initWithImage:macBookAir]; self.myImageView.center = self.view.center; [self.view addSubview:self.myImageView]; }
First, we need to make sure that we are initializing our image view using the initWithFrame: method, instead of the initWithImage: method, as the latter will set the width and height of the image view to the exact width and height of the image. So let’s remedy that first:
- (void)viewDidLoad { [super viewDidLoad]; UIImage *macBookAir = [UIImage imageNamed:@"MacBookAir"]; self.myImageView = [[UIImageView alloc] initWithFrame:self.view.bounds]; self.myImageView.contentMode = UIViewContentModeScaleAspectFit; self.myImageView.image = macBookAir; self.myImageView.center = self.view.center; [self.view addSubview:self.myImageView]; }
This property is of type UIContentMode:
typedef NS_ENUM(NSInteger, UIViewContentMode) { UIViewContentModeScaleToFill, UIViewContentModeScaleAspectFit, UIViewContentModeScaleAspectFill, UIViewContentModeRedraw, UIViewContentModeCenter, UIViewContentModeTop, UIViewContentModeBottom, UIViewContentModeLeft, UIViewContentModeRight, UIViewContentModeTopLeft, UIViewContentModeTopRight, UIViewContentModeBottomLeft, UIViewContentModeBottomRight, };
Here is an explanation of some of the most useful values in the UIViewContentMode enumeration:
UIViewContentModeScaleToFill This will scale the image inside the image view to fill the entire boundaries of the image view.
UIViewContentModeScaleAspectFit This will make sure the image inside the image view will have the right aspect ratio and fits inside the image view’s boundaries.
UIViewContentModeScaleAspectFill This will makes sure the image inside the image view will have the right aspect ratio and fills the entire boundaries of the image view. For this value to work properly, make sure that you have set the clipsToBounds property of the image view to YES.
So to make sure the image fits into the image view’s boundaries and that the aspect ratio of the image is right, we need to use the UIViewContentModeScaleAspectFit content mode:
- (void)viewDidLoad { [super viewDidLoad]; UIImage *macBookAir = [UIImage imageNamed:@"MacBookAir"]; self.myImageView = [[UIImageView alloc] initWithFrame:self.view.bounds]; self.myImageView.contentMode = UIViewContentModeScaleAspectFit; self.myImageView.image = macBookAir; self.myImageView.center = self.view.center; [self.view addSubview:self.myImageView]; }