Question

In iOS, I would like to create a line segment object and animate its start and end points (I can do this in Microsoft's WPF).

Currently, I create a line segment object as a tiny CALayer that I stretch and rotate using a transform.

+(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;
}

I can animate this line segment by changing its transform.

This works semi-good, but not perfectly, since, during the animation, the end points does not follow straight lines, as I would like. I therefore wonder if there is a better method to create a line segment object that I can animate?

Was it helpful?

Solution

You can use a CAShapeLayer and create a CGPath containing only two control points. The path property of CAShapeLayer itself actually is animatable (as long as the new path has the same number of points) plus you get all the transform capabilities of CALayer. And as Tommy just mentioned, you can play with strokeStart and strokeEnd for some pretty cool animations (there also is lineDashPatternwhich animates nicely with lineDashPhasebut i guess you won't need that).

Code Sample from 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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top