Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS aspect fit and center

Tags:

ios

uiview

I'd like to call

[self.view setContentMode:UIViewContentModeScaleAspectFit | UIViewContentModeCenter];

where self is an instance of UIViewController. This doesn't seem to work; what are the direct alternatives, if any?

like image 228
SK9 Avatar asked Aug 13 '11 07:08

SK9


People also ask

What is aspect fit in Swift?

The option to scale the content to fit the size of the view by maintaining the aspect ratio.

What is the difference between aspect fill and aspect fit when displaying an image?

The Fit setting will resize an image to fit within the bounds of its container with no cropping. The Fill setting will expand an image to fill the whole container, which may result in some cropping depending on the dimensions of your container and the image you send into it.

What is aspect fit?

"Aspect Fit" means "stretch this image up as large as it can go, but make sure that all the image is visible while keeping its original aspect ratio." This is useful when you want an image to be as large as possible without stretching its proportions, and it's probably the most commonly used content mode.

What is content mode?

The content mode specifies how the cached bitmap of the view's layer is adjusted when the view's bounds change. This property is often used to implement resizable controls.


2 Answers

You will need to set contentMode once when the view loads and then center it in viewWillLayoutSubviews which is called upon device rotation.

override func viewDidLoad() {
  super.viewDidLoad()
  //additional code to instantiate and setup image
  imageView.contentMode = .ScaleAspectFit
  self.view.addSubview(profileImageView)
}

override func viewWillLayoutSubviews() {
    imageView.center.x = view.center.x
    //or imageView.center = view.center
    //or imageView.center.y = view.center.y
}
like image 35
ericgu Avatar answered Nov 15 '22 08:11

ericgu


The contentMode is not a mask; you can't use | to combine values, you'll have to pick one. UIViewContentModeScaleAspectFit should center the content if it doesn't fit the view.

like image 181
jtbandes Avatar answered Nov 15 '22 08:11

jtbandes