Reputation: 39201
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:
This image is the result when "imageView.contentMode = UIViewContentModeCenter;
" is commented out:
EDIT:
This image is the result when I comment out both contentModes:
Upvotes: 2
Views: 2472
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
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