黑马程序员技术交流社区

标题: 音乐播放器类进度条(优化版) [打印本页]

作者: 叶子哥    时间: 2016-7-11 11:09
标题: 音乐播放器类进度条(优化版)


话不多说,先看GIF预览:


                                                                              
这个Demo中实现主要用到那些方面呢? 下面为你一一道来:

1.Quartz-2D
这里主要利用Quartz-2D的重绘功能,进度条的实时刷新.

  1. - (void)drawRect:(CGRect)rect {

  2.     CGPoint center = CGPointMake(rect.size.width*0.5, rect.size.height*0.5);
  3.     CGFloat radius = 100.0f;
  4.     CGFloat startAngle = - M_PI_2;
  5.     CGFloat endAngle = 2 * M_PI * self.valueChange - M_PI_2;
  6.     //大圆
  7.     UIBezierPath *path1 = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:0 endAngle:2 * M_PI clockwise:YES];
  8.    
  9.     [[UIColor darkGrayColor] set];
  10.     [path1 fill];
  11.    
  12.     //内圆
  13.     UIBezierPath *path2 = [UIBezierPath bezierPathWithArcCenter:center radius:radius - 5 startAngle:0 endAngle:2 * M_PI clockwise:YES];

  14.     [[UIColor whiteColor] set];
  15.     [path2 fill];

  16.     //显示的进度  圆形
  17.     UIBezierPath *path3 = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES];
  18.   
  19.     [path3 addLineToPoint:center];
  20.    
  21.     [[UIColor redColor] set];
  22.     [path3 fill];
  23.    
  24.     //剪切图片,并加载
  25.     [path2 addClip];
  26.     [[UIImage imageNamed:@"1"] drawInRect:rect];

  27.      //图片转动
  28.     [self rotateImage];
  29.    
  30.     }  
复制代码

2.自定义UISlider
重写方法和自定义代理方法,实现监听滑块拖动时,用户停止拖拽的事件,并进行判断,调用代理方法.

  1. @protocol  YYSliderDelegate <NSObject>
  2.     @optional
  3.     - (void)sliderWhenEndTracking:(YYSlider *)slider;
  4. @end   

  5.     - (void)endTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event{

  6.     if ([self.delegate respondsToSelector:@selector(sliderWhenEndTracking:)]) {
  7.         
  8.         [self.delegate sliderWhenEndTracking:self];
  9.     }
  10.     }
复制代码

3.设置定时器
这里的定时器主要用来调用改变进度的方法,如果用在真实的播放音乐上的话,可以根据不同的歌曲时间长度来相应设置.
    //开启定时器方法

  1.   - (void)startTimer{

  2.     NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.04 target:self selector:@selector(progressViewValueChange) userInfo:nil repeats:YES];
  3.     self.timer = timer;
  4.     [[NSRunLoop currentRunLoop]addTimer:timer forMode:NSRunLoopCommonModes];
  5.     }
复制代码


  //结束定时器方法

  1. - (void)endTimer{

  2.     [self.timer invalidate];
  3.     self.timer = nil;

  4.     }
复制代码


4.设置按钮的不同状态
根据不同的点击时间,按钮的状态会发生相应的变化.这里使用一个属性来记录点击时间,并封装设置按钮颜色和文字的方法.

  1.   - (void)setClickBtnWithTitle:(NSString *)title withColor:(UIColor *)color{

  2.     [self.beginBtn setBackgroundColor:color];
  3.     [self.beginBtn setTitle:title forState:UIControlStateNormal];

  4.     }
复制代码


结束语:
本Demo的实现思路很简单,可以活学活用.需要源代码的请戳这里:https://github.com/yaomars/MusicProgress






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2