2013-03-01 34 views
1

在iOS中,我想創建一個線段對象併爲其開始點和結束點(我可以在Microsoft的WPF中執行此操作)進行動畫處理。iOS中的動畫線段

目前,我創建了一個線段對象作爲一個小CALayer拉伸使用變換旋轉

+(LayLine*) layLineWithStartPoint:(CGPoint)ptStart andEndPoint:(CGPoint)ptEnd{ 
    LayLine* line = [[LayLine alloc] init]; 
    line.backgroundColor = [UIColor blackColor].CGColor; 
    line.frame = CGRectMake(0,-1,1,2); // Line 1 pixel long and 2 pixel wide line segment 
    line.anchorPoint = CGPointMake(0,0); 

    line.affineTransform = [LayLine affineTransformationForLineSegment:ptStart to:ptEnd]; 
    return line; 
} 

我可以通過改變其轉換來爲此線段生成動畫。

這個作品是半好的,但並不完美,因爲在動畫過程中,終點並不像我想的那樣沿着直線。因此,我想知道是否有更好的方法來創建可以製作動畫的線段對象?

+0

,你說什麼樣的動畫呢?這兩個點是否在不同的路徑上行進,或者它們是否位於同一條不變的路徑上的不同位置? – Tommy 2013-03-01 21:07:55

+0

@Tommy,我不知道我理解你的問題,但是ptStartA-ptEndA應該移動到ptStartB-ptEndB(線段B可能垂直於線段A)。 – ragnarius 2013-03-01 21:12:40

回答

3

您可以使用CAShapeLayer並創建僅包含兩個控制點的CGPath。 CAShapeLayer本身的路徑屬性實際上是動畫的(只要新路徑具有相同的點數),再加上您獲得CALayer的所有轉換功能。正如剛纔提到的Tommy,你可以使用strokeStartstrokeEnd來播放一些非常酷的動畫(也有lineDashPattern,它與lineDashPhase很好地吻合,但我想你不需要這樣做)。從this question

代碼示例:

CAShapeLayer *lineShape = nil; 
CGMutablePathRef linePath = nil; 
linePath = CGPathCreateMutable(); 
lineShape = [CAShapeLayer layer]; 

lineShape.lineWidth = 1.0f; 
lineShape.lineCap = kCALineJoinMiter; 
lineShape.strokeColor = [[UIColor redColor] CGColor]; 

CGPathMoveToPoint(linePath, NULL, x, y); 
CGPathAddLineToPoint(linePath, NULL, toX, toY); 

lineShape.path = linePath; 
CGPathRelease(linePath); 
+2

......我問的問題是相關的,因爲'strokeEnd'和'strokeStart'屬性也是動畫的,所以如果你感興趣的話,你可以單獨離開路徑並且動畫化它的哪一部分。我在我的一個應用程序中使用這個圓形進度條 - 這只是一個圓形路徑,它讓我們讓Core Animation執行「strokeEnd」的工作。 – Tommy 2013-03-01 21:31:04

+0

要動畫的路徑,我必須將其轉換爲NSValue莫名其妙? – ragnarius 2013-03-01 21:54:24

+1

我不知道你如何動畫..但CGPathRef可以橋接到'id'類型。請參閱http://stackoverflow.com/questions/9513082/cashapelayer-animating-path-glitches-flickers-from-ellipse-to-rect-and-back – 2013-03-01 22:05:18