UIView scaling during animation

后端 未结 6 1965
时光取名叫无心
时光取名叫无心 2020-12-05 03:25

I\'ve got a custom UIView to show a tiled image.

    - (void)drawRect:(CGRect)rect
    {
        ...
        CGContextRef context = UIGraphicsGetCurrentConte         


        
6条回答
  •  天涯浪人
    2020-12-05 04:11

    If it is not a big animation or performance isn't an issue for the animation duration, you can use a CADisplayLink. It does smooth out the animation of the scaling of a custom UIView drawing UIBezierPaths for instance. Below is a sample code you can adapt for your image.

    The ivars of my custom view contains displayLink as a CADisplayLink, and two CGRects: toFrame and fromFrame, as well as duration and startTime.

    - (void)yourAnimationMethodCall
    {
        toFrame = 
        fromFrame = self.frame; // current frame.
    
        [displayLink removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; // just in case    
        displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(animateFrame:)];
        startTime = CACurrentMediaTime();
        duration = 0.25;
        [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
    }
    
    - (void)animateFrame:(CADisplayLink *)link
    {
        CGFloat dt = ([link timestamp] - startTime) / duration;
    
        if (dt >= 1.0) {
            self.frame = toFrame;
            [displayLink removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
            displayLink = nil;
            return;
        }
    
        CGRect f = toFrame;
        f.size.height = (toFrame.size.height - fromFrame.size.height) * dt + fromFrame.size.height;
        self.frame = f;
    }
    

    Note that I haven't tested its performance, but it does work smoothly.

提交回复
热议问题