Friday, July 6, 2012

UIScrollview scrolling in a non linear fashion!

If you want to implement scrolling something like in the link its not possible using UIScrollView because the contentOffset of the scrollview will increase linearly. Don't worry you can modify the standard scrolling behavior by applying logic something like below code.
In the post I have implemented the UIScrollView in such a way that it scrolls like bazier path and there is a commented code for sine wave testing also. If you comment the bazier code and uncomment the sine wave code… Then the scollview scrolls like sine wave. Cool and simple isn't it :):):)

#Define POINT_A CGPointMake(0, 0)
#Define POINT_B CGPointMake(500, 1024*2)
#Define POINT_C CGPointMake(1000, 1024*1.5)
#Define POINT_D CGPointMake(1800, 0))

#define SCROLLVIEW_HEIGHT (768*3.0)

// simple linear interpolation between two points
CGPoint lerp(CGPoint dest, const CGPoint a, const CGPoint b, const float t)
    CGPoint outPoint;
    outPoint.x = a.x + (b.x-a.x)*t;
    outPoint.y = a.y + (b.y-a.y)*t;
    return outPoint;

// evaluate a point on a bezier-curve. t goes from 0 to 1.0
CGPoint bezier(CGPoint dest, const CGPoint a, const CGPoint b, const CGPoint c, const CGPoint d, const float t)
    CGPoint ab,bc,cd,abbc,bccd;
    ab = lerp(ab, a,b,t);           // point between a and b (green)
    bc = lerp(bc, b,c,t);           // point between b and c (green)
    cd = lerp(cd, c,d,t);           // point between c and d (green)
    abbc = lerp(abbc, ab,bc,t);       // point between ab and bc (blue)
    bccd = lerp(bccd, bc,cd,t);       // point between bc and cd (blue)
    dest = lerp(dest, abbc,bccd,t);   // point on the bezier-curve (black)

    return dest;

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
    float x = [scrollView contentOffset].x;  

    //Sin wave Testing
    //float y = 90 - sin((x / (768*3))*10)*80;

    //Bazier path
    // 4 points define the bezier-curve. These are the points used
    // for the example-images on this page.
    // Will work for n Points also
    CGPoint a = POINT_A;
    CGPoint b = POINT_B;
    CGPoint c = POINT_C;
    CGPoint d = POINT_D;

    CGPoint p = bezier(p, POINT_A, POINT_B, POINT_C, POINT_D,([scrollView contentOffset].x/SCROLLVIEW_HEIGHT));
    x = [scrollView contentOffset].x;
    y = p.y;

    scrollView.contentOffset = CGPointMake(x, y);

No comments:

Post a Comment