UIView frame bounds coming as 0,0

Kiran picture Kiran · Dec 12, 2011 · Viewed 7.5k times · Source

Environment: Xcode 4, ios 5, ipod touch 4th generation with retina display

I am trying to write a simple app that shows a video preview and capture a photo. For showing the preview, I am using the following code:

  // Create the session
    session = [[AVCaptureSession alloc] init];

    // Set preset to the highest available
    session.sessionPreset = AVCaptureSessionPresetPhoto;

    // Give the frame for preview
    CALayer *viewLayer = self.vPreview.layer;
    NSLog(@"viewLayer = %@", viewLayer);

    AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = 
    [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];

    captureVideoPreviewLayer.frame = self.vPreview.bounds;

    NSLog(@"Bounds: x:%d, y:%d,height:%d,width:%d",
          self.vPreview.bounds.origin.x,self.vPreview.bounds.origin.y,
          self.vPreview.bounds.size.height, self.vPreview.bounds.size.width);



    [self.vPreview.layer addSublayer:captureVideoPreviewLayer];

    // Get AV Device
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    NSError *error = nil;

    // Add Input from the above device
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
    if ( !input ) NSLog(@"ERROR: trying to open camera: %@", error);

    [session addInput:input];

I have the vPreview connected to an UIView on IB story board and it occupies the full screen. However, the frame always prints as 0,0,0,0 (x,y,h,w). Can some one pls tell me what is going wrong?

There are few more lines of code that set the output and runs the session. However, by this time, the frame is already wrong. Interestingly I can see the video preview however it shows in portrait where as my app is all landscape.

Answer

Craig Otis picture Craig Otis · Dec 12, 2011

In what method are you printing the frame? There's a good chance that the UIView either hasn't been created at the point in the code where you're doing the printing, or at the very least it hasn't been automatically sized by the system.

I would recommend checking the frame in another method, once the actual view has appeared in the screen, like in viewDidAppear:

- (void)viewDidAppear {
    NSLog(@"View frame is: %@", NSStringFromCGRect(self.vPreview.frame));
    [super viewDidAppear];
}

Note also that it's much easier to use the NSStringFromXXX methods to print the value of a primitive structure, instead of accessing the values individually.