objective c - What's the easiest way to animate a line? -
i creating app involves animating lines within workspace on time. current approach use code in drawrect
:
cgcontextsetstrokecolor(context, black); cgcontextbeginpath(context); cgcontextmovetopoint(context, startpoint.x, startpoint.y); cgcontextaddlinetopoint(context, finalpoint.x, finalpoint.y); cgcontextstrokepath(context);
...and setting timer run every 0.05 seconds update finalpoint
, call setneedsdisplay
.
i'm finding approach (when there's 5ish lines moving @ once) slows down app terribly, , such high refresh frequency, still appears jerky.
there must better way perform simple line drawing in animated line - i.e. saying want line start @ x1, y1 , stretching x2, y2 on given length of time. options this? need make perform faster , love rid of clunky timer.
thanks!
use cashapelayers, , combination of catransactions , cabasicanimation.
you can add given path shapelayer , let rendering.
a cashapelayer object has 2 properties called strokestart
, strokeend
, defines along path end of line should render. defaults 0.0 strokestart
, , 1.0 strokeend
.
if set path strokeend
starts @ 0.0, see no line.
you can animate, 0.0 1.0, strokeend
property , see line lengthen.
to change cashapelayer's implicit 0.25s default animation timing, can add function class, so:
-(void)animatestrokeend:(cgfloat)_strokeend { [catransaction begin]; cabasicanimation *animation = [cabasicanimation animationwithkeypath:keypath]; animation.duration = 2.0f; //or long want happen animation.fromvalue = [nsnumber numberwithfloat:self.strokeend]; // current strokeend value animation.tovalue = [nsnumber numberwithfloat:_strokeend]; //to end of path [catransaction setcompletionblock:^{ self.strokeend = _strokeend }]; [self addanimation:animation forkey:@"animatestrokeend"]; [catransaction commit]; }
you can pass value 0.0f 1.0f value of _strokeend
.
the setcompletionblock:
ensures value passing explicitly set after animation completes.
Comments
Post a Comment