自定义UISlider 可以显示缓冲进度

最近做项目的时候需要实现一个播放器,播放器拖动条需要实现 显示缓冲进度像这样:


test.png

google上看见一些实现方案,一种比较好的方案是重新绘制UISlider:

- (CGRect)trackRectForBounds:(CGRect)bounds{
    CGRect rect = [super trackRectForBounds:bounds];
    
    rect = CGRectInset(rect, 0, -0.5);
    
    return rect;
}

-(void)setPlayableProgress:(CGFloat)playableProgress{
    if (_playableProgress != playableProgress){
        _playableProgress = playableProgress;
        [self setNeedsDisplay];
    }
}

-(void)setFrame:(CGRect)frame{
    [super setFrame:frame];
    [self setNeedsDisplay];
}

-(void)setBounds:(CGRect)bounds{
    [super setBounds:bounds];
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect{
    
    [super drawRect:rect];
    CGContextRef c = UIGraphicsGetCurrentContext();
    
    [[UIColor brownColor] set];
    
    CGRect r = [self trackRectForBounds:self.bounds];
    r = CGRectInset(r, 0, 0);
    UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:r cornerRadius:r.size.height/2.0];
    CGContextAddPath(c, bezierPath.CGPath);
    CGContextSetLineWidth(c, 1);
    CGContextStrokePath(c);
    CGContextAddPath(c, bezierPath.CGPath);
    CGContextClip(c);
    CGContextFillRect(c, CGRectMake(r.origin.x, r.origin.y, r.size.width * _playableProgress, r.size.height));
}

但是这种方案还是显得有点生硬,而且每次都重新绘画UISlider是的效率也变得比较低。

还是自定义UISlider 比较好用!
先看看头文件:MyPlayProgressView.h

#import 

@protocol MyPlayProgressViewDelegate 
// 开始拖动
- (void)beiginSliderScrubbing;
// 结束拖动
- (void)endSliderScrubbing;
// 拖动值发生改变
- (void)sliderScrubbing;
@end

@interface MyPlayProgressView : UIView

@property (nonatomic, weak) id delegate;

@property (nonatomic, assign) CGFloat minimumValue;
@property (nonatomic, assign) CGFloat maximumValue;

@property (nonatomic, assign) CGFloat value;
@property (nonatomic, assign) CGFloat trackValue;

@property (nonatomic, strong) UIColor *playProgressBackgoundColor;
@property (nonatomic, strong) UIColor *trackBackgoundColor;
@property (nonatomic, strong) UIColor *progressBackgoundColor;

@end

注意:playProgressBackgoundColor 是背景颜色,trackBackgoundColor 是显示缓冲进度的颜色,progressBackgoundColor是已经播放进度的颜色

minimumValue 默认最小值是0,maximumValue默认最小值是1

看看效果吧!

自定义UISlider 可以显示缓冲进度_第1张图片
Paste_Image.png

github源码:https://github.com/wmf00032/Resource

你可能感兴趣的:(自定义UISlider 可以显示缓冲进度)