Calculating marching ants

UnknownAlthough I use a CADisplayLink to update my dashed-selection overlay, I don’t want my marching ants overlay to depend on that timer for phase.

To that end, I worked away at a solution where I specify the speed of the progression (the seconds it takes to complete a frame) and calculate an offset based on the current time. I like this timing solution a lot better than ones that update a counter every time the display link pings, plus it lets me slow down the link’s frame interval without worrying about changing the update speed.

I’ve been using this to power a user-selected area today and it’s had no problem on-device with slightly older units in testing using CA Instruments. I’m still not in love with marching ants — moving things on my screen bother me a bit — but I did like the bit about using real time you see here.

- (void) drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClearRect(context, rect);

    CGFloat dashes[] = {12, 3};
    CGFloat distance = 15;
    CGFloat secondsPerFrame = 0.75f; // adjust as desired

    NSTimeInterval ti = [NSDate timeIntervalSinceReferenceDate] / secondsPerFrame;

    BOOL goesCW = YES;
    CGFloat phase = distance * (ti - floor(ti)) * (goesCW ? -1 : 1);
    [path setLineDash:dashes count:2 phase:phase];
    [path stroke:1 color:WHITE_LEVEL(0.75, 1)];
}

Comments are closed.