CAShapeLayer仿進度條

  • 先看下簡單效果
shapeLayer.gif

先簡單的介紹下CAShapeLayer

 1.CAShapeLayer繼承自CALayer,可使用CALayer的所有屬性(Shape:形狀)
 2.CAShapeLayer需要和貝塞爾曲線配合使用才有意義。貝塞爾曲線可以為其提供形狀,而單獨使用CAShapeLayer是沒有任何意義的。
 3.使用CAShapeLayer與貝塞爾曲線可以實現不在view的DrawRect方法中畫出一些想要的圖形

關于CAShapeLayer和DrawRect的比較

 1.DrawRect:DrawRect屬于CoreGraphic框架,占用CPU,消耗性能大
 2.CAShapeLayer:CAShapeLayer屬于CoreAnimation框架,通過GPU來渲染圖形,節省性能。動畫渲染直接提交給手機GPU,不消耗內存

貝塞爾曲線與CAShapeLayer的關系

  1.CAShapeLayer中shape代表形狀的意思,所以需要形狀才能生效
  2.貝塞爾曲線可以創建基于矢量的路徑
  3.貝塞爾曲線給CAShapeLayer提供路徑,CAShapeLayer在提供的路徑中進行渲染。路徑會閉環,所以繪制出了Shape
  4.用于CAShapeLayer的貝塞爾曲線作為Path,其path是一個首尾相接的閉環的曲線,即使該貝塞爾曲線不是一個閉環的曲線
  • 說完了簡介們來看一下如何創建一個簡單的圓形進度條
#import "ViewController.h"
@interface ViewController ()
{
    CGFloat add;
}
@property(nonatomic,strong)NSTimer *timer;
@property(nonatomic,strong)CAShapeLayer *shapeLayer;
@end
@implementation ViewController
//定時器
       - (NSTimer *)timer
{
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.1
                                                  target:self
                                                selector:@selector(timeAction)
                                                userInfo:nil
                                                 repeats:YES];
                 }
return _timer;
}
//定時器方法 
  - (void)timeAction
{
    if(self.shapeLayer.strokeEnd > 1 && self.shapeLayer.strokeStart < 1)
    {
        self.shapeLayer.strokeStart += add;
    }
    else
    if (self.shapeLayer.strokeStart == 0)
    {
        self.shapeLayer.strokeEnd += add;
    }
    if (self.shapeLayer.strokeEnd == 0)
    {
        self.shapeLayer.strokeStart = 0;
    }
    if (self.shapeLayer.strokeStart == self.shapeLayer.strokeEnd)
    {
        self.shapeLayer.strokeEnd = 0;
    }
}
  - (void)viewDidLoad {
    [super viewDidLoad];
    //創建shapeLayer
    self.shapeLayer = [CAShapeLayer layer];
    self.shapeLayer.frame = CGRectMake(self.view.center.x - 100, self.view.center.y - 100, 200, 200);
    self.shapeLayer.fillColor = [UIColor clearColor].CGColor;
    //設置shapeLayer邊框線
    self.shapeLayer.lineWidth = 1.0f;
    //邊框線顏色給個隨機色
    self.shapeLayer.strokeColor = [UIColor colorWithRed:arc4random() % 256 / 255.0 green:arc4random() % 256 / 255.0 blue:arc4random() % 256 / 255.0 alpha:1].CGColor;
    //創建圓形貝塞爾曲線
    UIBezierPath *bezierPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, 200, 200)];
    //shapelayer關聯貝塞爾曲線
    self.shapeLayer.path = bezierPath.CGPath;
    [self.view.layer addSublayer:self.shapeLayer];
    
    //設置stroke的起始點 1為一整圈
    self.shapeLayer.strokeStart = 0;
    self.shapeLayer.strokeEnd = 0;
    //遞增量
    add = 0.1;
    self.timer.fireDate = [NSDate distantPast];
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容