iOS上動態繪製曲線
近期需要完成一個功能,就是要在螢幕上動態地完成繪製一個曲線。這個曲線可以用來完成描述資料在一定時間內的變化等。大概就是下面這個效果。
這個效果要如何來完成呢?需要用到這三個類 UIBezierPath CAShapeLayer 和 CABasicAnimation 。其中UIBezierPath用來繪製相應地曲線路徑,CAShapeLayer用來為Path提供展示的位置,並且將CABasicAnimation所建立的動畫加入到Path之上。
<喎?http://www.bkjia.com/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+ICAgytfPyM7Sw8e9q87Sw8fL+c+jzfu1xHBhdGi0tL2os/bAtKO6PC9wPgo8cD4gICA8cHJlIGNsYXNzPQ=="brush:java;">UIBezierPath *path = [UIBezierPath bezierPath]; [path moveToPoint:CGPointMake(0.0,20.0)]; [path addLineToPoint:CGPointMake(120.0, 500.0)];[path addLineToPoint:CGPointMake(220, 0)]; [path addLineToPoint:CGPointMake(310, 40)]; [path addLineToPoint:CGPointMake(SCREEN_WIDTH, 110)];
然後我們再為CAShapeLayer建立自己的屬性,並且將我們的path賦值給它。如果沒有這個賦值的話,這個layer就不能為我們畫出這個效果了,並且也是一個不完整的layer.
CAShapeLayer *pathLayer = [CAShapeLayer layer]; pathLayer.frame = self.view.bounds; pathLayer.path = path.CGPath; pathLayer.strokeColor = [[UIColor redColor] CGColor]; pathLayer.fillColor = nil; pathLayer.lineWidth = 2.0f; pathLayer.lineJoin = kCALineJoinBevel; [self.view.layer addSublayer:pathLayer];
最後,我們將動畫賦值給我們的layer.我們的動畫效果中,可以改變其中的一些參數來控制它的繪畫效果。
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"]; pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"]; pathAnimation.duration = 2.0; pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f]; pathAnimation.toValue = [NSNumber numberWithFloat:1.0f]; [pathLayer addAnimation:pathAnimation forKey:@"strokeEnd"];
現在我們運行這些代碼,就可以獲得前面圖片中的效果了~