[英]Animation - Drawing a circle in iOS - Not animating complete circle
我正在使用以下代碼繪制圓的一部分。 但是,我有點困惑,因為在動畫結束時,它似乎立即填充了圓圈的其余部分。 為什么會這樣呢?
// Set up the shape of the circle
int radius = 62;
CAShapeLayer *circle = [CAShapeLayer layer];
// Make a circular shape
circle.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 2.0*radius, 2.0*radius)
cornerRadius:radius].CGPath;
// Center the shape in self.view
circle.position = CGPointMake(18, 92);
// Configure the apperence of the circle
circle.fillColor = [UIColor clearColor].CGColor;
circle.strokeColor = [UIColor whiteColor].CGColor;
circle.lineWidth = 5;
// Add to parent layer
[cell.layer addSublayer:circle];
// Configure animation
CABasicAnimation *drawAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
drawAnimation.duration = .8; // "animate over 10 seconds or so.."
drawAnimation.repeatCount = 1.0; // Animate only once..
// Animate from no part of the stroke being drawn to the entire stroke being drawn
drawAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
drawAnimation.toValue = [NSNumber numberWithFloat:0.4f];
// Experiment with timing to get the appearence to look the way you want
drawAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
發生這種情況是因為默認情況下,完成時會從圖層中刪除CAAnimation
。 這意味着它將在動畫結束后立即刪除您設置動畫的值,並將其設置為默認值1.0
。 由於您使用的是CAAnimation
該圖層實際上從未更改其屬性,而只是看起來是這樣,這就是為什么在刪除動畫時將其設置為1.0
原因,這就是該圖層的strokeEnd
值,因為您從未更改過。 嘗試通過在動畫發生時打印strokeEnd
的值來自己查看。
這可以通過兩種方式解決:在啟動動畫之前設置最終的storkeEnd
值,以使其在刪除時仍為0.4
或者通過向CABasicAnimation
添加某些屬性來解決。 您需要設置以實現所需內容的屬性是:
drawAnimation.fillMode = kCAFillModeForwards
和
drawAnimation.removedOnCompletion = false
希望能有所幫助
對於要進行動畫drawAnimation.fromValue
的整個筆畫, drawAnimation.fromValue
應該為0.0
而drawAnimation.toValue
應該為1.0
。 這些值確定筆畫的動畫百分比。
drawAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
drawAnimation.toValue = [NSNumber numberWithFloat:1.0f];
fromValue : Defines the value the receiver uses to start interpolation.
toValue : Defines the value the receiver uses to end interpolation.
您使用的是0.4
作為drawAnimation.toValue
。 因此,它在動畫的40%
處結束,並在不設置動畫的情況下一次性繪制其余部分。
例如,如果您設置drawAnimation.fromValue = 0.5
和drawAnimation.toValue = 1.0
,則動畫將從半個圓圈開始。 如果將drawAnimation.fromValue = 0.0
設置drawAnimation.fromValue = 0.0
drawAnimation.toValue = 0.5
,則動畫將以半圈結束,其余部分將不進行動畫繪制。
如果只想繪制40%的圓,則可以使用其他函數來創建圓路徑。
CGFloat startAngle = (-M_PI/2);
CGFloat endAngle = startAngle + 0.4*(2*M_PI);
circle.path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(radius, radius)
radius:radius
startAngle:startAngle
endAngle:endAngle
clockwise:YES].CGPath;
上面的代碼實際上從startAngle = -M_PI/2
生成了40%的圓形路徑。 您可以根據需要改變角度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.