一.绘制进度条
在研究了Quartz 2D绘制路径、文字之后,我们需要实例运用一下。首先我们制作一个如下的效果,拖动slider的时候,扇形的进度条也随之加载。

思路:
- 需要一个slider、一个view来绘制扇形;
- 当slider拖动的时候,把slider滑动到的value值给view来绘制扇形;
- 扇形最小弧度是0,最大弧度是360度(M_PI * 2);扇形的起点是-M_PI_2,终点是slider滑动的value * 360度(M_PI * 2);
实现
我们再storyboard里面添加一个slider、一个ProgressView,ProgressView里面添加一个valueLabel来显示进度;

viewcontroller:
#import "ViewController.h"
#import "ProgressView.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet ProgressView *progressView;
@end
@implementation ViewController
//滚动条滚动调用的事件
- (IBAction)sliderValueChange:(UISlider *)sender {
//把滚动的值传给显示的view
self. progressView.value = sender.value;
}
@end
ProgressView:
.h
@interface ProgressView : UIView
//用于接收滚动的值
@property(nonatomic,assign)CGFloat value;
@end
.m
@implementation ProgressView
-(void)setValue:(CGFloat)value{
_value = value;
//修改lable显示的内容
_valueLabel.text = [NSString stringWithFormat:@"%.2f%%",value * 100];
//通知系统,调用drawRect方法
[self setNeedsDisplay];
}
/*
当系统调用drawRect方法时,在drawRect内部会自动创建跟view相关的上下文
手动调用drawRect不会创建上下文
*/
- (void)drawRect:(CGRect)rect {
CGPoint center = CGPointMake(rect.size.width * 0.5, rect.size.height *0.5);
CGFloat radius = rect.size.width/2.0 - 10;
CGFloat startA = -M_PI_2;//-90度
CGFloat endA = startA + _value * M_PI * 2; //value * 360度
//1.获取上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
//2.描绘路径
UIBezierPath * path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES];
[path addLineToPoint:center];
//设置上下文状态
[[UIColor yellowColor] set];
//3.把路径添加到画板上面
CGContextAddPath(ctx, path.CGPath);
//4.把上下文渲染到view的layer层
[path fill];
}
@end
网友评论