前言
最近比較閑,正好利用這段時間把現在項目用的東西封裝一下,方便以后復用,當然好的東西還是要分享。一起學習,一起進步。
看圖片,很顯然這是一個扇形圖,相信大家對做扇形圖得心應手,可能對做扇形動畫有一定難度,不急,下面給出代碼和思路。
針對項目用的扇形動畫,在這個基礎上我做了一下封裝。
核心代碼如下:
-(instancetype)initWithCenter:(CGPoint)center radius:(CGFloat)radius bgColor:(UIColor *)bgColor repeatCount:(NSInteger)repeatCount { if (self = [super init]) { //設置self的frame和center self.backgroundColor = bgColor; self.frame = CGRectMake(0, 0, radius * 2, radius * 2); self.center = center; _repeatCount = repeatCount; //特別注意:貝塞爾曲線的radius必須為self高度的四分之一,CAShapeLayer的線寬必須為self高度的二分之一 UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(radius, radius) radius:radius / 2 startAngle:-M_PI/2 endAngle:M_PI *3 / 2 clockwise:YES]; CAShapeLayer *maskLayer = [CAShapeLayer layer]; maskLayer.path = path.CGPath; maskLayer.fillColor = [UIColor clearColor].CGColor; maskLayer.strokeColor = bgColor.CGColor; maskLayer.lineWidth = radius; //等于半徑的2倍,以圓的邊緣為中心,向圓內部伸展一個半徑,向外伸展一個半徑,所以看上去以為圓的半徑是self高度的一半。 self.layer.mask = maskLayer; _maskLayer = maskLayer; } return self;}-(void)startAnimaiton { //開始執行扇形動畫 CABasicAnimation *strokeEndAni = [CABasicAnimation animationWithKeyPath:@"strokeEnd"]; strokeEndAni.fromValue = @0; strokeEndAni.toValue = @1; strokeEndAni.duration = 1; //重復次數 strokeEndAni.repeatCount = _repeatCount; [_maskLayer addAnimation:strokeEndAni forKey:@"ani"];}
思路
可以讓fillcolor 為clearcolor 讓linewidth充滿整個圓,然后讓strokeend執行動畫,從而實現扇形動畫。
下載地址:源碼下載 | 本地下載
調用方法很簡單:直接看API
/**初始化對象@param center 中心@param radius self寬度的一半@param bgColor 背景色@param repeatCount 動畫重復次數@return self*/-(instancetype)initWithCenter:(CGPoint)center radius:(CGFloat)radius bgColor:(UIColor *)bgColor repeatCount:(NSInteger)repeatCount;-(void)startAnimaiton;-(void)puaseAnimation;
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對武林網的支持。
新聞熱點
疑難解答