views:

110

answers:

3

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.

+3  A: 

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.

If you're putting imageView inside something called superview, you could do this:

CGPoint superCenter = CGPointMake([superview bounds].size.width / 2.0, [superview bounds].size.height / 2.0);
[imageView setCenter:superCenter];
quixoto
A: 
CGRect r = thingToCenter.frame;
r.origin = parentView.bounds.origin;
r.origin.x = parentView.bounds.size.width / 2  - r.size.width / 2;
r.origin.y = parentView.bounds.size.height / 2  - r.size.height / 2 + 12;
thingToCenter.frame = r;
DexterW
A: 

Position the imageView in the parentView based on the size and origin of the parentView's rect.

Given a parent view named parentView:

float parentRect = parentView.frame;
float imageRect = imageView.frame;

imageRect.origin.x = (int)(parentView.origin.x + (parentRect.size.width - imageRece.size.width) / 2);
imageRect.origin.x = (int)(parentView.origin.y + (parentRect.size.height- imageRece.size.height) / 2);
imageView.frame = imageRect;

Casting the origins to int ensures that your centered image is not blurry (though it may be off center by a subpixel amount).

Peter