美文网首页
iOS开发之虚线动画

iOS开发之虚线动画

作者: 小璐有大大的梦想 | 来源:发表于2016-09-24 17:18 被阅读0次

    实现虚线动画
    效果就是下面这张图循环动起来:


    iOS开发之虚线动画

    实现:

    /**
     * lineView:       需要绘制成虚线的view
     * lineLength:     虚线的宽度
     * lineSpacing:    虚线的间距
     * lineColor:      虚线的颜色
     **/
    - (void)drawDashLine:(UIView *)lineView lineLength:(int)lineLength lineSpacing:(int)lineSpacing lineColor:(UIColor *)lineColor
    {
        //  设置路径
        UIBezierPath *path      = [UIBezierPath bezierPathWithRect:lineView.bounds];
    
        CAShapeLayer *shapeLayer = [CAShapeLayer layer];
        [shapeLayer setBounds:lineView.bounds];
        [shapeLayer setFillColor:[UIColor clearColor].CGColor];
        //  设置虚线颜色为blackColor
        [shapeLayer setStrokeColor:lineColor.CGColor];
        //  设置虚线宽度
        [shapeLayer setLineWidth:3.f];
        // 设置线条圆角
        [shapeLayer setLineCap:kCALineJoinRound];
        //  设置线宽,线间距
        [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:@(lineLength),@(lineSpacing), nil]];
        //设置路径
        [shapeLayer setPath:path.CGPath];
        [lineView.layer addSublayer:shapeLayer];
        //加动画
        CABasicAnimation *dashAnimation = [CABasicAnimation
                                           animationWithKeyPath:@"lineDashPhase"];
        [dashAnimation setFromValue:[NSNumber numberWithFloat:0.0f]];
        [dashAnimation setToValue:[NSNumber numberWithFloat:300.f]];
        [dashAnimation setDuration:4.f];
        dashAnimation.cumulative = YES; //关键属性,自己看文档
        [dashAnimation setRepeatCount:MAXFLOAT];
        dashAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
        [shapeLayer addAnimation:dashAnimation forKey:@"linePhase"];
    }
    

    加载实现:

        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(self.view.center.x, self.view.center.y, 100,100)];
        [self.view addSubview:lineView];
        [self drawDashLine:lineView lineLength:16 lineSpacing:15 lineColor:[UIColor redColor]];
    

    相关文章

      网友评论

          本文标题:iOS开发之虚线动画

          本文链接:https://www.haomeiwen.com/subject/jxvxyttx.html