iOS 餅狀圖(扇形圖)動畫效果的實現

先上效果圖:


23.gif

Demo在此,休得撒野!!!!

1.怎么用

/**
 *  Pie
 *
 *  @param frame      frame
 *  @param dataItems  數據源,此Demo是紅、綠、藍比例為1:4:5
 *  @param colorItems 對應數據的pie的顏色,如果colorItems.count < dataItems 或
 *                      colorItems 為nil 會隨機填充顏色
 *
 */
- (id)initWithFrame:(CGRect)frame
          dataItems:(NSArray *)dataItems
         colorItems:(NSArray *)colorItems;
/**
 *  開始動畫
 */
- (void)stroke;

2.算法分析

圖層分析

以紅色部分開始為例計算
r:扇形半徑
center:PieView中心位置
start:開始位置,范圍[0,1]
end:結束位置,范圍[0,1]
?:相對于y軸(-π/2)扇形中間位置的角度
  ? = 2 * π * (start + 1/2.0 * (end - start)) = π * (start + end)
??x:labelCenter到y軸距離
  ??x = 1/2.0 * r * sin(?)
??y:labelCenter到y軸距離
  ??y = 1/2.0 * r * cos(?)
labelCenter:百分比label的center
  labelCenterX = center.x + ??x
  labelCenterY = center.y - ??y

3. PieView.m部分

- (id)initWithFrame:(CGRect)frame dataItems:(NSArray *)dataItems colorItems:(NSArray *)colorItems
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.hidden = YES;
        self.backgroundColor = kPieBackgroundColor;
       
        //1.pieView中心點
        CGFloat centerWidth = self.frame.size.width * 0.5f;
        CGFloat centerHeight = self.frame.size.height * 0.5f;
        CGFloat centerX = centerWidth;
        CGFloat centerY = centerHeight;
        CGPoint centerPoint = CGPointMake(centerX, centerY);
        CGFloat radiusBasic = centerWidth > centerHeight ? centerHeight : centerWidth;
        
        //計算紅綠藍部分總和
        _total = 0.0f;
        for (int i = 0; i < dataItems.count; i++) {
            _total += [dataItems[i] floatValue];
        }
        
        //線的半徑為扇形半徑的一半,線寬是扇形半徑,這樣就能畫出圓形了
        //2.背景路徑
        CGFloat bgRadius = radiusBasic * 0.5;
        UIBezierPath *bgPath = [UIBezierPath bezierPathWithArcCenter:centerPoint
                                                              radius:bgRadius
                                                          startAngle:-M_PI_2
                                                            endAngle:M_PI_2 * 3
                                                           clockwise:YES];
        _bgCircleLayer = [CAShapeLayer layer];
        _bgCircleLayer.fillColor   = [UIColor clearColor].CGColor;
        _bgCircleLayer.strokeColor = [UIColor lightGrayColor].CGColor;
        _bgCircleLayer.strokeStart = 0.0f;
        _bgCircleLayer.strokeEnd   = 1.0f;
        _bgCircleLayer.zPosition   = 1;
        _bgCircleLayer.lineWidth   = bgRadius * 2.0f;
        _bgCircleLayer.path        = bgPath.CGPath;
        
        
        //3.子扇區路徑
        CGFloat otherRadius = radiusBasic * 0.5 - 3.0;
        UIBezierPath *otherPath = [UIBezierPath bezierPathWithArcCenter:centerPoint
                                                                 radius:otherRadius
                                                             startAngle:-M_PI_2
                                                               endAngle:M_PI_2 * 3
                                                              clockwise:YES];
        
        CGFloat start = 0.0f;
        CGFloat end = 0.0f;
        for (int i = 0; i < dataItems.count; i++) {
            //4.計算當前end位置 = 上一個結束位置 + 當前部分百分比
            end = [dataItems[i] floatValue] / _total + start;
            
            //圖層
            CAShapeLayer *pie = [CAShapeLayer layer];
            [self.layer addSublayer:pie];
            pie.fillColor   = kPieFillColor;
            if (i > colorItems.count - 1 || !colorItems  || colorItems.count == 0) {//如果傳過來的顏色數組少于item個數則隨機填充顏色
                pie.strokeColor = kPieRandColor.CGColor;
            } else {
                pie.strokeColor = ((UIColor *)colorItems[i]).CGColor;
            }
            pie.strokeStart = start;
            pie.strokeEnd   = end;
            pie.lineWidth   = otherRadius * 2.0f;
            pie.zPosition   = 2;
            pie.path        = otherPath.CGPath;
            
            
            //計算百分比label的位置
            CGFloat centerAngle = M_PI * (start + end);
            CGFloat labelCenterX = kLabelLoctionRatio * sinf(centerAngle) + centerX;
            CGFloat labelCenterY = -kLabelLoctionRatio * cosf(centerAngle) + centerY;
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, radiusBasic * 0.7f, radiusBasic * 0.7f)];
            label.center = CGPointMake(labelCenterX, labelCenterY);
            label.text = [NSString stringWithFormat:@"%ld%%",(NSInteger)((end - start + 0.005) * 100)];
            label.textAlignment = NSTextAlignmentCenter;
            label.textColor = [UIColor whiteColor];
            label.layer.zPosition = 3;
            [self addSubview:label];
            
            
            //計算下一個start位置 = 當前end位置
            start = end;
        }
        self.layer.mask = _bgCircleLayer;
        
    }
    return self;
}

</br>

- (void)stroke
{
    //畫圖動畫
    self.hidden = NO;
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    animation.duration  = kAnimationDuration;
    animation.fromValue = @0.0f;
    animation.toValue   = @1.0f;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    animation.removedOnCompletion = YES;
    [_bgCircleLayer addAnimation:animation forKey:@"circleAnimation"];
}

4. 結束

頗多不足,敬請指教!!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容