Ccscrollview: Add a scroll bar and scroll background

Source: Internet
Author: User

The ccscrollview provided in the cocos2d-X does not provide the scroll bar and scroll bar background, and I made some modifications to it, using the cocos2d-x version 3.0



Usage

   CCBarScrollView* scrollView = CCBarScrollView::create();    scrollView->initWithViewSize((Size(280.0f,150.0f)));    scrollView->setContentSize(Size(280,150*10.0f));    scrollView->setDirection(cocos2d::extension::ScrollView::Direction::VERTICAL);    scrollView->setPosition(Point(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));    scrollView->setBounceable(true);    this->addChild(scrollView,0);        auto bgImage = Scale9Sprite::create("bg_pd_item.png");    auto barImage = Scale9Sprite::create("bg2.png");        scrollView->setBarImage(bgImage, barImage);//    scrollView->setAutoHidden(true);        for (int i = 0; i < 50; i++) {        auto sprite1 = Sprite::create("CloseNormal.png");        sprite1->setPosition(20, 20+i*40);        scrollView->addChild(sprite1);    }

Control Code: Click the open link


Class ccbarscrollview: Public scrollview {public: static ccbarscrollview * Create (size, node * Container = NULL); static ccbarscrollview * Create (); using node: addchild; void setbarimage (scale9sprite * barbg, scale9sprite * barimage); Virtual void addchild (node * child, int zorder, int tag) override; void setcontentoffset (point offset, bool animated = false ); void setautohidden (bool autohidden); // sets whether to automatically hide virtual bool ontouchbegan (touch * touch, event * event); Virtual void ontouchended (touch * touch, event * event ); protected: void deacceleratescrolling };


Set the scroll bar background and scroll bar

void CCBarScrollView::setBarImage(Scale9Sprite* barBg, Scale9Sprite* barImage){        Size contentSize = this->getContentSize();    auto layer1 = LayerColor::create(Color4B(255, 0, 255, 255), contentSize.width, contentSize.height);    layer1->setCascadeColorEnabled(false);    layer1->setPosition( Point(0, 0));    this->addChild(layer1);        Size viewSize = this->getViewSize();    this->barBg = barBg;        this->barBg->setContentSize(Size(20,viewSize.height));    this->barBg->setPosition(Point(viewSize.width - 10,viewSize.height/2));    this->barImage = barImage;    Layer::addChild(this->barBg);    Layer::addChild(this->barImage);        this->barImage->setContentSize(Size(20,viewSize.height*(viewSize.height/contentSize.height)));        this->updateBarPos();}


Set whether the scroll bar is automatically hidden

void CCBarScrollView::setAutoHidden(bool autoHidden){    this->isAutoHidden = autoHidden;        if(this->barImage != nullptr && this->isAutoHidden == true)    {        this->barImage->setVisible(false);    }}

In the parent class, addchild adds the child node to the rolling iner, but the scroll bar and background should be on its parent node. Therefore, the method must be reloaded.

void CCBarScrollView::addChild(Node *child, int zOrder, int tag){    if (_container != child && barBg != child && barImage != child)    {        _container->addChild(child, zOrder, tag);    } else    {        Layer::addChild(child, zOrder, tag);    }}

When the contentoffset changes, you must update the position of the scroll bar.

void CCBarScrollView::setContentOffset(Point offset, bool animated/* = false*/){    if (animated)    { //animate scrolling        this->setContentOffsetInDuration(offset, BOUNCE_DURATION);    }    else    { //set the container position directly        if (!_bounceable)        {            const Point minOffset = this->minContainerOffset();            const Point maxOffset = this->maxContainerOffset();                        offset.x = MAX(minOffset.x, MIN(maxOffset.x, offset.x));            offset.y = MAX(minOffset.y, MIN(maxOffset.y, offset.y));        }                _container->setPosition(offset);                if (_delegate != NULL)        {            _delegate->scrollViewDidScroll(this);        }    }    this->updateBarPos();//    CCLOG("CCBarScrollView::setContentOffset");}

Function for updating the position of a scroll bar

void CCBarScrollView::updateBarPos(){//    Point currentOffset = this->_container->getPosition();    Point currentOffset = this->getContentOffset();    Size contentSize = this->getContentSize();    Size viewSize = this->getViewSize();        Size barSize = this->barImage->getContentSize();    Point p =Point(viewSize.width-10,barSize.height/2 + viewSize.height*(-currentOffset.y/contentSize.height));   //    CCLOG("barImage %f,%f,%f,%f",p.x,p.y,barSize.width,barSize.height);//    CCLOG("currentOffset %f",currentOffset.y);    if(p.y < barSize.height/2)    {        p.y = barSize.height/2;    }    else if(p.y + barSize.height/2 > viewSize.height)    {        p.y = viewSize.height- barSize.height/2;    }        this->barImage->setPosition(p);}

When the scroll bar is clicked and released, it will slow down, so the corresponding processing needs to be done in the deceleration function.

void CCBarScrollView::deaccelerateScrolling(float dt){    if (_dragging)    {        this->unschedule(schedule_selector(CCBarScrollView::deaccelerateScrolling));        return;    }        float newX, newY;    Point maxInset, minInset;        _container->setPosition(_container->getPosition() + _scrollDistance);        if (_bounceable)    {        maxInset = _maxInset;        minInset = _minInset;    }    else    {        maxInset = this->maxContainerOffset();        minInset = this->minContainerOffset();    }        newX = _container->getPosition().x;    newY = _container->getPosition().y;        _scrollDistance     = _scrollDistance * SCROLL_DEACCEL_RATE;    this->setContentOffset(Point(newX,newY));        if ((fabsf(_scrollDistance.x) <= SCROLL_DEACCEL_DIST &&         fabsf(_scrollDistance.y) <= SCROLL_DEACCEL_DIST) ||        newY >= maxInset.y || newY <= minInset.y ||        newX >= maxInset.x || newX <= minInset.x)    {                if(this->isAutoHidden)        {            FiniteTimeAction *faseOut;            faseOut = FadeOut::create(0.2);            this->barImage->runAction(faseOut);        }        this->unschedule(schedule_selector(CCBarScrollView::deaccelerateScrolling));        this->relocateContainer(true);    }            this->updateBarPos();}

Click Event start and end Processing

bool CCBarScrollView::onTouchBegan(Touch* touch, Event* event){    if (!this->isVisible())    {        return false;    }            Rect frame = getViewRect();        //dispatcher does not know about clipping. reject touches outside visible bounds.    if (_touches.size() > 2 ||        _touchMoved          ||        !frame.containsPoint(touch->getLocation()))    {        CCLOG("outside visible bounds.");        return false;    }        if (std::find(_touches.begin(), _touches.end(), touch) == _touches.end())    {        _touches.push_back(touch);        //        CCLOG("_touches.push_back");    }        if (_touches.size() == 1)    { // scrolling        _touchPoint     = this->convertTouchToNodeSpace(touch);        _touchMoved     = false;        _dragging     = true; //dragging started        _scrollDistance = Point(0.0f, 0.0f);        _touchLength    = 0.0f;                if(isAutoHidden)        {            FiniteTimeAction *faseIn;            faseIn = FadeIn::create(0.2);            this->barImage->setVisible(true);            this->barImage->setOpacity(0);            this->barImage->runAction(faseIn);        }                //        CCLOG("scrolling");    }    else if (_touches.size() == 2)    {        _touchPoint = (this->convertTouchToNodeSpace(_touches[0]).getMidpoint(                                                                              this->convertTouchToNodeSpace(_touches[1])));                _touchLength = _container->convertTouchToNodeSpace(_touches[0]).getDistance(                                                                                    _container->convertTouchToNodeSpace(_touches[1]));                _dragging  = false;        this->barImage->setVisible(false);        //        CCLOG("_dragging");    }    return true;}

void CCBarScrollView::onTouchEnded(Touch* touch, Event* event){    if (!this->isVisible())    {        return;    }        auto touchIter = std::find(_touches.begin(), _touches.end(), touch);    bool isDeaccelerateScrolling = false;    if (touchIter != _touches.end())    {        if (_touches.size() == 1 && _touchMoved)        {            isDeaccelerateScrolling = true;            this->schedule(schedule_selector(CCBarScrollView::deaccelerateScrolling));        }        _touches.erase(touchIter);    }        if (_touches.size() == 0)    {        if(this->isAutoHidden && isDeaccelerateScrolling == false)        {            FiniteTimeAction *faseOut;            faseOut = FadeOut::create(0.2);            this->barImage->runAction(faseOut);        }        _dragging = false;        _touchMoved = false;    }}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.