Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

centering a CGRect in a view

Tags:

I have an image displaying in a CGRect. how do I center the rect in the view?

here's my code:

UIImage * image = [UIImage imageNamed:place.image]; CGRect rect = CGRectMake(10.0f, 90.0f, image.size.width, image.size.height);  UIImageView * imageView = [[UIImageView alloc] initWithFrame:rect]; [imageView setImage:image]; 

I've tried imageView.center but to no effect.

thanks in advance.

like image 363
hanumanDev Avatar asked Sep 09 '10 15:09

hanumanDev


People also ask

How do I center an image in Xcode?

Select your image view and apply width and height constraints via the pin dialogue box (screenshot below), then open your alignment constraints and select center horizontally and center vertically. Then just apply your constraints and voila!

What is Cgrect in Swift?

A structure that contains the location and dimensions of a rectangle.


2 Answers

Looking at:

https://developer.apple.com/documentation/coregraphics/cggeometry

You can do:

CGPoint center = CGPointMake(CGRectGetMidX(mainRect), CGRectGetMidY(mainRect)); 
like image 198
Kitt Hirasaki Avatar answered Oct 11 '22 01:10

Kitt Hirasaki


UIView's center is a property, not a method.

You need to calculate the actual location you want to put it in. You can do this by setting the frame of the view, or by setting its center, which is simpler in your case.

You don't say what view you then go make imageView a subview of. If you're putting it inside something called superview, you could do this:

CGPoint superCenter = CGPointMake(CGRectGetMidX([superview bounds]), CGRectGetMidY([superview bounds])); [imageView setCenter:superCenter]; 
like image 26
Ben Zotto Avatar answered Oct 11 '22 02:10

Ben Zotto