Esqarrouth
Esqarrouth

Reputation: 39201

Center & Aspect Fit Image

Currently I can not set 2 content modes at the same time it seems. But I want the image both scaled and centered. How do I accomplish this?

@property (weak, nonatomic) IBOutlet UIView *windowOut;

self.windowOut.layer.borderColor = [UIColor redColor].CGColor;
self.windowOut.layer.borderWidth = 3.0f;

UIImage *face = [UIImage imageNamed:@"face.png"];

UIImageView* imageView = [[UIImageView alloc] initWithFrame:self.windowOut.frame];
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.contentMode = UIViewContentModeCenter;

[imageView setImage:face];
[self.windowOut addSubview:imageView];

This image is the result with the code above: enter image description here

This image is the result when "imageView.contentMode = UIViewContentModeCenter; " is commented out: enter image description here

EDIT: This image is the result when I comment out both contentModes: enter image description here

Upvotes: 2

Views: 2472

Answers (2)

Hermann Klecker
Hermann Klecker

Reputation: 14068

The reason it is not centered is here:

UIImageView* imageView = [[UIImageView alloc] initWithFrame:self.windowOut.frame];

[self.windowOut addSubview:imageView];

That works only when windowOut happens to be located at (0/0). .frame gives the frame in its superview's coordinate system. If windowOut is located at, let's say (20/20) within its superview (self.view?) then imageView will be located at (40,40).

Use bounds instead. That is the same but within its own coordinate system.

UIImageView* imageView = [[UIImageView alloc] initWithFrame:self.windowOut.bounds];
[self.windowOut addSubview:imageView];

Upvotes: 2

user2105505
user2105505

Reputation: 708

If the imageView is set to the same frame as its superview, and the content mode is UIViewContentModeScaleAspectFit, then it should be centered by definition. Good luck!

Upvotes: 0

Related Questions