CALayer behaves differently when creating anew vs when applying CATransform3dIdentity

时间:2015-06-15 15:17:16

标签: ios calayer caanimation

I am really stuck with some CALayer knowledge missing.

I have a layer which knows how to draw an arrow.

I apply some transform on every frame on it.

But it only works as expected if I always create this layer from scratch and apply the transform. And it doesn't work if I try reusing the same old layer (by applying a CATransform3dIdentity). Through "it doesn't work" I mean it flickers on the screen and the transform is not applied as needed as compared to the transform applied to the newly created layer.

My code looks as follows:

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
{
    transformModel = [OverlayTransformExtractor transformFromPixelBuffer:sampleBuffer];

    if(transformModel)
    {
        //I tried also not removing it every time but just transforming.. the effect is the same
        [firstLayer removeFromSuperlayer];

        if(!firstLayer)
        {
            firstLayer = [VNArrowLayer layer];

            firstLayer.frame = CGRectMake(videoView.frame.origin.x, videoView.frame.origin.y, videoView.frame.size.width, videoView.frame.size.height);
            originalTransform = firstLayer.transform;
        }

        //resetting the previous transforms
        firstLayer.transform = CATransform3DIdentity;

        [self applyTransform:transformModel.transform];

        dispatch_async(dispatch_get_main_queue(), ^(void)
        {
            [arrowView.layer addSublayer:firstLayer];

            [CATransaction begin];
            [CATransaction setValue:(id)kCFBooleanTrue
                             forKey:kCATransactionDisableActions];
            [firstLayer setNeedsDisplay];
            [CATransaction commit];

        });
    }
    else
    {
        dispatch_async(dispatch_get_main_queue(), ^
        {
          [firstLayer removeFromSuperlayer];
            [secondLayer removeFromSuperlayer];
        });
    }
}

Some suggestions of why is it behaving differently when it's just created? I checked the transform to be the same. I even tried to set the same position as a new layer (0,0), but the it is even more weird (it remains in the left top corner)

I also thought that maybe it's because of the implicit animation, so I tried turning it off -> no change.

Adding a new layer every time is not acceptable. The memory becomes full pretty fast, even though I manually try setting the firstLayer to nil.

1 个答案:

答案 0 :(得分:0)

如上所述,当我将变换应用于现有图层(每一帧)时,它会闪烁。在每一帧创建时都很完美,但内存密集。

我无法得到什么使它闪烁,可能是一些约束或布局的东西,我找不到任何信息,但..

我设法使这种方法(每一帧的新层)都有效。我的想法是,我正在移除旧图层,并在主线程上分配nil,这导致deallocations在后期发生并以这种方式快速填充我的记忆。

所以解决方法是删除旧图层,创建新图层并在主线程上应用转换。

如果smb可以提供解释闪烁的答案,我很乐意将其标记为正确的。