Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I would do it with an animated property. </p> <p>To achieve this I would create a custom <code>CALayer</code> class - let's call it <code>LineLayer</code>. Define a <code>startPoint</code> property, and a <code>length</code> property. I'd then configure the <code>length</code> property to be "animatable". </p> <p>The code for that would look something like the following:</p> <pre><code>// LineLayer.h @interface LineLayer: CALayer @property (nonatomic, assign) int length; // This was omitted from the SO code snippet. @property (nonatomic, assign) CGPoint startPoint; @end // LineLayer.m @implementation LineLayer @synthesize length = _length; // This was omitted from the SO code snippet. @synthesize startPoint= _startPoint; - (id) initWithLayer:(id)layer { if(self = [super initWithLayer:layer]) { if([layer isKindOfClass:[LineLayer class]]) { // This bit is required for when we CA is interpolating the values. LineLayer *other = (LineLayer*)layer; self.length = other.length; self.startPoint = other.startPoint; // This was omitted. } } return self; } + (BOOL)needsDisplayForKey:(NSString *)key { if ([key isEqualToString:@"length"]) { return YES; } return [super needsDisplayForKey:key]; } - (void) setLength:(int)newLength { if (newLength &lt; 0) { return; // Fail early. } _length = newLength; [self setNeedsDisplay]; } /* This should have been drawInContext:(CGContextRef)context - (void) drawRect:(CGRect) rect */ - (void) drawInContext:(CGContextRef)context { //...Do your regular drawing here. // This was omitted from the SO code snippet. CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor); CGContextSetLineWidth(context, 2); CGContextMoveToPoint(context, _startPoint.x, _startPoint.y); CGContextAddLineToPoint(context, _startPoint.x + _length, _startPoint.y); CGContextStrokePath(context); } @end </code></pre> <p>Then in your view controller you could use <code>LineLayer</code> like this:</p> <pre><code>- (void)viewDidLoad { [super viewDidLoad]; LineLayer *lineLayer = [LineLayer new]; // This was omitted from the SO code snippet. lineLayer.frame = CGRectMake(0, 0, 320, 480); [lineLayer setNeedsDisplay]; // --- lineLayer.startPoint = CGPointMake(0, 100); lineLayer.length = 0; [self.view.layer addSublayer:lineLayer]; // Now animate the changes to the length property CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"length"]; anim.duration = 5; // Change should table about 5 mins. anim.fromValue = [NSNumber numberWithInt:0]; anim.toValue = [NSNumber numberWithInt:200]; [lineLayer addAnimation:anim forKey:@"animateLength"]; lineLayer.length = 200; //Do clean up below... } </code></pre> <p>Happy Coding :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload