Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIView.center = UIImageView.center but image view doesn't seem to be in centre in landscape

Tags:

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

enter image description here


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]))];
like image 256
TeaCupApp Avatar asked Dec 21 '11 10:12

TeaCupApp


People also ask

How do I change aspect ratio in UIImageView?

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.

What is the difference between a UIImage and a UIImageView?

UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .

What is UIImageView?

An object that manages image data in your app.


1 Answers

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.

like image 108
jrturton Avatar answered Sep 21 '22 17:09

jrturton