Sandah Aung
Sandah Aung

Reputation: 6188

Centre a UIImageView inside a CGRect

I would like to centre a UIImageView inside a rectangular region on an iOS screen. The location and dimensions of the rectangle are determined at runtime and are represented by a CGRect. The image has already been drawn but has to move to the centre of the rectangular region at runtime. How can I achieve this?

Upvotes: 1

Views: 109

Answers (2)

BradzTech
BradzTech

Reputation: 2835

Assuming you want the change to occur instantaneously, you should simply be able to change the frame for the image view to your desired CGRect:

imageView.frame = rect

This is assuming your UIImageView autosizes and/or has the correct aspect ratio. If not, you should adjust your CGRect accordingly. Alternatively, you can look into animating the frame property.

If you're just going to be doing this when the view initially loads, it would be much easier center the image with Auto Layout by horizontally and vertically centering it in its container, as Duncan C suggested.

Upvotes: 0

Duncan C
Duncan C

Reputation: 131491

It depends. If you are using auto-layout (the default) then you would use layout constraints. You should be able to set up layout constraints in IB that would keep the image view centered even if it changes size, without requiring any custom code.

Simply Select the view in IB, choose the button at the right that gives you a popup titled "Add New Alignment Constraints" and click the checkboxes "Horizontal Center in Container" and "Vertical Center in Container". Then click the "Add constraints" button at the bottom of the popup.

Upvotes: 1

Related Questions