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?
[imageView setCenter:CGPointMake(CGRectGetMidX([dynamicMainView bounds]), CGRectGetMidY([dynamicMainView bounds]))];
To maintain aspect ratio I calculated the width of UIImageView = (320/460)*450 = 313.043 dynamically. And set the contentMode For UIImageView is UIViewContentModeScaleAspectFit. And set the image(320x460) to image view but it is some what blur.
UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .
An object that manages image data in your app.
The center
of 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 bounds
rectangle of view B. You can get this using (from memory!) CGRectGetMidX
and CGRectGetMidY
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With