iOS实现音频进度条效果

2020-01-21 07:28:01于海丽

画图方法:


/**
 初始化layer 在完成frame赋值后调用一下
 */
-(void)initLayers{
 [self initStrokeLayer];
 [self setBackColorLayer];
}

绘制路径


/*路径*/
-(void)initStrokeLayer{
 UIBezierPath *path = [UIBezierPath bezierPath];
 CGFloat maxWidth = self.frame.size.width;
 CGFloat drawHeight = self.frame.size.height;
 CGFloat x = 0.0;
 while (x+kDrawLineWidth<=maxWidth) {
 CGFloat random =5+ arc4random()%differenceValue;//差值在1-50 之间取
 NSLog(@"%f",random);
 [path moveToPoint:CGPointMake(x-kDrawLineWidth/2, random)];
 [path addLineToPoint:CGPointMake(x-kDrawLineWidth/2, drawHeight-random)];
 x+=kDrawLineWidth;
 x+=kDrawMargin;
 }
 self.shapeLayer.path = path.CGPath;
 self.backColorLayer.path = path.CGPath;
}

设置mask来显示黄色路径


/*设置masklayer*/
-(void)setBackColorLayer{
 UIBezierPath *path = [UIBezierPath bezierPath];
 [path moveToPoint:CGPointMake(0, self.frame.size.height/2)];
 [path addLineToPoint:CGPointMake(self.frame.size.width, self.frame.size.height/2)];
 self.maskLayer.frame = self.bounds;
 self.maskLayer.lineWidth = self.frame.size.width;
 self.maskLayer.path= path.CGPath;
 self.backColorLayer.mask = self.maskLayer;
}

手动设置百分比的两个方法


-(void)setAnimationPersentage:(CGFloat)persentage{
 CGFloat startPersentage = self.persentage;
 [self setPersentage:persentage];

 CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
 pathAnimation.duration = 1;
 pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
 pathAnimation.fromValue = [NSNumber numberWithFloat:startPersentage];
 pathAnimation.toValue = [NSNumber numberWithFloat:persentage];
 pathAnimation.autoreverses = NO;
 pathAnimation.delegate = self;
 [self.maskLayer addAnimation:pathAnimation forKey:@"strokeEndAnimation"];
}
/**
 * 在修改百分比的时候,修改遮罩的大小
 *
 * @param persentage 百分比
 */
- (void)setPersentage:(CGFloat)persentage {

 _persentage = persentage;
 self.maskLayer.strokeEnd = persentage;
}

最终使用