tarmes
tarmes

Reputation: 15442

How to force redraw of a CALayer during an animation that changes its bounds

I have a layer-hosting NSView. Within that I have a CALayer which includes a drawInContext method. The needsDisplayOnBoundsChange parameter is set to true, and and if I resize the view then the layer is indeed resized and redrawn during correctly during the animation.

However, I'd like to animate the size of the layer independently of the view. I can set up an animation to do this, however the layer isn't redrawn during the animation. Rather, is seems that a snap shot is taken for the start and end frames and one is faded out as the other is faded in. Worse, both images are distorted into the resizing-frame as the animation progresses.

How can I force the CALayer to redraw itself during the resize animation?

Thanks,

Tim

Upvotes: 1

Views: 1798

Answers (1)

felinira
felinira

Reputation: 1634

This is probably too old but the solution shouldn't be too hard. I don't know if there is a better way but you can just use a CADisplayLink which sets your layer to need redrawing.

- (void)updateContinuously
{
    if(!self.displayLink) {
        self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateLayer)];
        [self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
    }
}

- (void)stopUpdatingContinuously
{
    [self.displayLink invalidate];
    self.displayLink = nil;
}

- (void)update
{
    // This will fire every time when the display is redrawn
    [self setNeedsDisplay];
}

- (void)updateContinuouslyForTime:(NSTimeInterval)seconds
{
    // Create an NSTimer that will remove the displayLink when the time is over
    NSTimer *stopTimer = [NSTimer scheduledTimerWithTimeInterval:seconds target:self selector:@selector(stopUpdatingContinuously) userInfo:nil repeats:NO];
    [[NSRunLoop mainRunLoop] addTimer:stopTimer forMode:NSRunLoopCommonModes];
}

Upvotes: 0

Related Questions