在iOS中,我想创建一个线段对象并为其起点和终点设置动画(我可以在Microsoft的WPF中执行此操作)。
目前,我创建了一个线段对象作为一个小的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 :(得分:3)
您可以使用CAShapeLayer并创建仅包含两个控制点的CGPath。 CAShapeLayer本身的path属性实际上是可动画的(只要新路径具有相同的点数),您就可以获得CALayer的所有转换功能。正如Tommy刚刚提到的那样,您可以使用strokeStart
和strokeEnd
来播放一些非常酷的动画(还有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);