user3332086 user3332086 - 1 month ago 14
iOS Question

Get all X,Y coordinates between two points in objective C

How to get all X,Y coordinates between two points.
I want to move a UIButton in a diagonal pattern in objective C.
Example. To move UIButton from position 'Point A' towards position 'Point B'.

.Point B

. Point A

Thanks in advance.


you can use Bresenham's line algorithm

Here is a slightly simplified version, I have used a bunch of times

+(NSArray*)getAllPointsFromPoint:(CGPoint)fPoint toPoint:(CGPoint)tPoint
    /*Simplified implementation of Bresenham's line algoritme */
    NSMutableArray *ret = [NSMutableArray array];
    float deltaX = fabsf(tPoint.x - fPoint.x);
    float deltaY = fabsf(tPoint.y - fPoint.y);
    float x = fPoint.x;
    float y = fPoint.y;
    float err = deltaX-deltaY;

    float sx = -0.5;
    float sy = -0.5;
        sx = 0.5;

        sy = 0.5;
    do {
        [ret addObject:[NSValue valueWithCGPoint:CGPointMake(x, y)]];
        float e = 2*err;
        if(e > -deltaY)
            err -=deltaY;
            x +=sx; 
        if(e < deltaX)
            err +=deltaX;
    } while (round(x)  != round(tPoint.x) && round(y) != round(tPoint.y));
    [ret addObject:[NSValue valueWithCGPoint:tPoint]];//add final point
    return ret;

If you simply want to animate a UIControl from one location to another, you might want to use UIAnimation:

[UIView animateWithDuration:1.0f delay:0.0f options:UIViewAnimationOptionCurveLinear animations:^{ = CGPointMake(<NEW_X>, <NEW_Y>)
} completion:^(BOOL finished) {