I am making application for iPad, only landscape mode will be supported. I am having a UIView and later I am dynamically adding UIImageView as a subview. However my goal is to add images in centre of the UIView. So I used this code,
[imageView setCenter:dynamicMainView.center];
where imageView is UIImageView(Obvious :)) and dynamicMainView is UIView, However final outcome docent seem to be in centre,
Visual Representation

Full method code for adding UIImageView in UIView is,
-(void) addImageIntoMainDynamicView:(UIImage *) image
{
[self clearImageFromMainDynamicView];//Always clear Dynamic main view before adding new views
imageView = [[UIImageView alloc] initWithImage:image];
if(imageView.bounds.size.width > dynamicMainView.bounds.size.width || imageView.bounds.size.height > dynamicMainView.bounds.size.height)
{
[imageView setFrame:[dynamicMainView bounds]];
}
[imageView setCenter:dynamicMainView.center];
NSLog(@"Image : X = %f and Y = %f", imageView.center.x,imageView.center.y );
NSLog(@"UIView : X = %f and Y = %f", dynamicMainView.center.x,dynamicMainView.center.y );
[dynamicMainView addSubview:imageView];
[imageView release];
}
And above log value is,
2011-12-21 21:07:11.850 Map1TestApp[94645:11603] Image : X = 512.000000 and Y = 371.500000
2011-12-21 21:07:11.853 Map1TestApp[94645:11603] UIView : X = 512.000000 and Y = 371.500000
Any clue about why it’s not adding in centre? Am I doing something wrong?
FOR FUTURE VIEWER THE ANWSER WAS :
[imageView setCenter:CGPointMake(CGRectGetMidX([dynamicMainView bounds]), CGRectGetMidY([dynamicMainView bounds]))];
The
centerof a view is expressed in it’s superview’s coordinate system. So you are centering your image view in the wrong coordinate system. (dynamic view’s superview as opposed to dynamic view)To centre view A within view B, the centre point of view A has to be the centre of the
boundsrectangle of view B. You can get this using (from memory!)CGRectGetMidXandCGRectGetMidY.