录音波形图的实现
在项目中我们需要实现一个动画特效,就是根据录音的分贝数来显示动画,线条长度代表分贝数,线条左右位置,逐渐变淡来代表时间,话不多说,下面介绍代码
1.创建一个视图view的子类:RecordWaveView
一个数组属性:waves,用来存储分贝数据
一个方法:-(void)setRecordWaveWithDecibel:(CGFloat)decibel,用来传入分贝数据,显示动画
初始化视图
-(instancetype)initWithFrame:(CGRect)frame{ if(self=[super initWithFrame:frame]){ self.backgroundColor=[UIColor clearColor]; } return self; }
画动画图,设置一个数组waves,waves中存储的是分贝数,然后将数组画在试图上:
-(void)drawRect:(CGRect)rect{ CGFloat w=self.frame.size.width/2; CGFloat h=self.frame.size.height; { CGFloat n=[self.waves[i] floatValue]; UIBezierPath*linePath=[UIBezierPath bezierPath]; [linePath moveToPoint:SPPoint(w-30-i*5, (h-n)/2)]; [linePath addLineToPoint:SPPoint(w-30-i*5, (h+n)/2)]; linePath.lineWidth=2; [[UIColor colorWithRed:250/255.0 green:127/255.0 blue:0/255.0 alpha:1-i/10.0f] setStroke]; [linePath stroke]; }循环块:0-self.waves.count的循环; { CGFloat n=[self.waves[i] floatValue]; UIBezierPath*linePath=[UIBezierPath bezierPath]; [linePath moveToPoint:SPPoint(w+30+i*5, (h-n)/2)]; [linePath addLineToPoint:SPPoint(w+30+i*5, (h+n)/2)]; linePath.lineWidth=2; [[UIColor colorWithRed:250/255.0 green:127/255.0 blue:0/255.0 alpha:1-i/10.0f] setStroke]; [linePath stroke]; }循环块:0-self.waves.count的循环; }
实现方法,让画的视图动起来
-(void)setRecordWaveWithDecibel:(CGFloat)decibel{ if(self.waves.count<10){ [self.waves insertObject:[NSNumber numberWithFloat:decibel] atIndex:0]; } else{ [self.waves removeLastObject]; [self.waves insertObject:[NSNumber numberWithFloat:decibel] atIndex:0]; } [self setNeedsDisplay]; }