【问题标题】:UIView frame bounds coming as 0,0UIView 框架边界为 0,0
【发布时间】:2011-12-11 23:15:12
【问题描述】:

环境:Xcode 4、ios 5、ipod touch 4th generation with Retina display

我正在尝试编写一个显示视频预览和拍摄照片的简单应用。为了显示预览,我使用以下代码:

  // 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];

我将 vPreview 连接到 IB 故事板上的 UIView,它占据了全屏。但是,帧总是打印为 0,0,0,0 (x,y,h,w)。有人可以告诉我出了什么问题吗?

还有几行代码可以设置输出并运行会话。然而,到了这个时候,框架已经是错误的了。有趣的是,我可以看到视频预览,但它以纵向显示,而我的应用程序全是横向。

【问题讨论】:

  • 只是评论:要记录CGRect 这很好用NSLog(@"%@",NSStringFromCGRect(self.vPreview.bounds));
  • 感谢 NJones,将使用它。我仍在从 C++ 世界转型

标签: iphone uiview ios5 ipod avcapturesession


【解决方案1】:

你用什么方法打印框架?很有可能UIView 没有在您正在执行打印的代码中创建,或者至少它没有被系统自动调整大小。

我建议用另一种方法检查框架,一旦实际视图出现在屏幕上,例如viewDidAppear:

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

还要注意,使用NSStringFromXXX 方法打印原始结构的值要比单独访问这些值要容易得多。

【讨论】:

    【解决方案2】:

    该代码很可能在从 NIB 文件实际加载视图之前以 init 方法运行。所以当你调用self.vPreview.bounds 时,self.vPreview 实际上是 nil,给出一个零 CGRect 返回值。

    使用 UIViewController,视图是延迟加载的,所以直到有东西请求视图属性,笔尖才被加载。

    您应该在-viewDidLoad 方法中进行视图自定义。一旦加载了 nib 就会调用它,并且所有连接的 IBOutlets 都将是非 nil。

    【讨论】:

      猜你喜欢
      • 2011-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-19
      • 2011-01-01
      • 2011-11-08
      相关资源
      最近更新 更多