使用CAShapeLayer与UIBezierPath可以实现不在view的drawRect方法中就画出一些想要的图形
步骤:
1、新建UIBezierPath对象bezierPath
2、新建CAShapeLayer对象caShapeLayer
3、将bezierPath的CGPath赋值给caShapeLayer的path,即caShapeLayer.path = bezierPath.CGPath
4、把caShapeLayer添加到某个显示该图形的layer中
下面的小例子是一个环形的progress代码,有具体的使用方法
.h文件:
- #import <QuartzCore/QuartzCore.h>
- #import <UIKit/UIKit.h>
- @interface KACircleProgressView : UIView {
- CAShapeLayer *_trackLayer;
- UIBezierPath *_trackPath;
- CAShapeLayer *_progressLayer;
- UIBezierPath *_progressPath;
- }
- @property (nonatomic, strong) UIColor *trackColor;
- @property (nonatomic, strong) UIColor *progressColor;
- @property (nonatomic) float progress;//0~1之间的数
- @property (nonatomic) float progressWidth;
- - (void)setProgress:(float)progress animated:(BOOL)animated;
- @end
.m文件
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
_progressLayer = [CAShapeLayer new];
[self.layer addSublayer:_progressLayer];
_progressLayer.fillColor = nil;
_progressLayer.lineCap = kCALineCapRound;
_progressLayer.frame = self.bounds;
//默认5
self.progressWidth = 5;
}
return self;
}
- (void)setProgress
{
_progressPath = [UIBezierPath bezierPathWithArcCenter:(CGPointMake(self.center.x, 0)) radius:130 startAngle:M_PI endAngle:M_PI * _progress - M_PI clockwise:YES];
_progressLayer.path = _progressPath.CGPath;
}
//设置进度条的宽度
- (void)setProgressWidth:(float)progressWidth
{
_progressWidth = progressWidth;
_progressLayer.lineWidth = _progressWidth;
[self setProgress];
}
- (void)setProgressColor:(UIColor *)progressColor
{
_progressLayer.strokeColor = progressColor.CGColor;
}
//设置进度
- (void)setProgress:(float)progress
{
_progress = progress;
[self setProgress];
}
- (void)setProgress:(float)progress animated:(BOOL)animated
{
[self setProgress:progress];
// 给这个layer添加动画效果
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
pathAnimation.duration = progress;
pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
[_progressLayer addAnimation:pathAnimation forKey:nil];
}
使用:
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- // Do any additional setup after loading the view, typically from a nib.
- KACircleProgressView *progress = [[KACircleProgressView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
- [self.view addSubview:progress];
- progress.trackColor = [UIColor blackColor];
- progress.progressColor = [UIColor orangeColor];
- progress.progress = .7;
- progress.progressWidth = 10;
- }
最后上一张效果图:
- (
center:圆心的坐标
radius:半径
startAngle:起始的弧度
endAngle:圆弧结束的弧度
clockwise:YES为顺时针,No为逆时针
转载请注明出处,多谢