iOS上動態繪製曲線

來源:互聯網
上載者:User

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"];

現在我們運行這些代碼,就可以獲得前面圖片中的效果了~

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.