1. 程式人生 > >iOS-利用UIBezierPath和CAAnimation製作心跳動畫

iOS-利用UIBezierPath和CAAnimation製作心跳動畫

空閒之餘,練習下UIBezierPath進行繪圖和CAAnimation動畫的使用,製作了一個心跳的動畫,很簡單的示例

GIF示例:

核心程式碼

1-首先通過 drawRect 繪製心形view

- (void)drawRect:(CGRect)rect { 
    // 間距
    CGFloat padding = 4.0;
    // 半徑(小圓半徑)
    CGFloat curveRadius = (rect.size.width - 2 * padding)/4.0;
    // 貝塞爾曲線
    UIBezierPath *heartPath = [UIBezierPath bezierPath];
    // 起點(圓的第一個點)
CGPoint tipLocation = CGPointMake(rect.size.width/2, rect.size.height-padding); // 從起點開始畫 [heartPath moveToPoint:tipLocation]; // (左圓的第二個點) CGPoint topLeftCurveStart = CGPointMake(padding, rect.size.height/2.4); // 新增二次曲線 [heartPath addQuadCurveToPoint:topLeftCurveStart controlPoint:CGPointMake(topLeftCurveStart.x
, topLeftCurveStart.y + curveRadius)]; // 畫圓 [heartPath addArcWithCenter:CGPointMake(topLeftCurveStart.x+curveRadius, topLeftCurveStart.y) radius:curveRadius startAngle:M_PI endAngle:0 clockwise:YES]; // (左圓的第二個點) CGPoint topRightCurveStart = CGPointMake(topLeftCurveStart.x + 2*curveRadius, topLeftCurveStart.y
); // 畫圓 [heartPath addArcWithCenter:CGPointMake(topRightCurveStart.x+curveRadius, topRightCurveStart.y) radius:curveRadius startAngle:M_PI endAngle:0 clockwise:YES]; // 右上角控制點 CGPoint topRightCurveEnd = CGPointMake(topLeftCurveStart.x + 4*curveRadius, topRightCurveStart.y); // 新增二次曲線 [heartPath addQuadCurveToPoint:tipLocation controlPoint:CGPointMake(topRightCurveEnd.x, topRightCurveEnd.y+curveRadius)]; // 設定填充色 [[UIColor redColor] setFill]; // 填充 [heartPath fill]; // 設定邊線 heartPath.lineWidth = 2; heartPath.lineCapStyle = kCGLineCapRound; heartPath.lineJoinStyle = kCGLineJoinRound; // 設定描邊色 [[UIColor yellowColor] setStroke]; [heartPath stroke]; }

2-新增心形view到主檢視

    XMHeartView *heartView = [[XMHeartView alloc] init];
    heartView.frame = CGRectMake(100, 50, 200, 200);
    [self.view addSubview:heartView];

3-給心形view新增心跳動畫

// 給心檢視新增心跳動畫
    float bigSize = 1.1;
    CABasicAnimation *pulseAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    pulseAnimation.duration = 0.5;
    pulseAnimation.toValue = [NSNumber numberWithFloat:bigSize];
    pulseAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    // 倒轉動畫
    pulseAnimation.autoreverses = YES;
    // 設定重複次數為無限大
    pulseAnimation.repeatCount = FLT_MAX;
    // 新增動畫到layer
    [heartView.layer addAnimation:pulseAnimation forKey:@"transform.scale"];