Search code examples
cocos2d-iphoneccscrollview

How can I control the size of a CCScrollView?


When using a CCScrollView I would like to be able to limit the viewable area to a certain bounding box. How can this be achieved?

Setting the content size does not affect the viewable area.


Solution

  • So I found what seems to be a reasonable way to do this. There was some code on the cocos2d forum for clipping an area using GL_SCISSOR:

    http://forum.cocos2d-swift.org/t/cocos2d-3-1-beta-gl-scissor-test/13608/4

    -(void)visit:(CCRenderer *)renderer parentTransform:(const GLKMatrix4 *)parentTransform
    {
        CGPoint positionInWorldCoords = [self convertToWorldSpace:ccp(0, 0)];
        CGFloat contentScaleFactor = [[CCDirector sharedDirector] contentScaleFactor];
    
        positionInWorldCoords = ccpMult(positionInWorldCoords, contentScaleFactor);
    
    
        [renderer enqueueBlock:^{
            glEnable(GL_SCISSOR_TEST);
            glScissor(positionInWorldCoords.x, positionInWorldCoords.y, self.contentSize.width * contentScaleFactor, self.contentSize.height * contentScaleFactor);
    } globalSortOrder:0 debugLabel:nil threadSafe:YES];
    
        [super visit:renderer parentTransform:parentTransform];
    
        [renderer enqueueBlock:^{
            glDisable(GL_SCISSOR_TEST);
        } globalSortOrder:0 debugLabel:nil threadSafe:YES];
    }
    

    So I subclassed CCScrollView and added this method. I ended up having to tweak the coordinates a bit to get the exact right clipping area. Seems like a clunky answer so I hope someone has a better answer.