zoukankan      html  css  js  c++  java
  • cocos2d-x3.x 设计与实现弹出对话框

    要定义一个类PopupLayer


    代码PopupLayer.h


    #ifndef __crossDT_PopupLayer__
    #define __crossDT_PopupLayer__
    
    #include "cocos2d.h"
    #include "cocos-ext.h"
    USING_NS_CC;
    using namespace cocos2d::extension;
    
    class PopupLayer :public Layer
    {
    public:
    	PopupLayer();
    	~PopupLayer();
    	virtual bool init();
    	CREATE_FUNC(PopupLayer);
    
    	//virtual void registerWithTouchDispatcher(void);
    	bool onTouchBegan(Touch *touch, Event *unused_event);
    
    	static PopupLayer * create(const char* backgroundImage);
    	void setTitle(const char* title ,int fontsize=20);
    	void setContentText(const char* text ,int fontsize=20 ,int padding=50 ,int paddintTop=100);
    	void setCallbackFunc(Object* target, SEL_CallFuncN callfun);
    	
    	bool addButton(const char* normalImage, const char* selectedImage, const char* title, int tag=0);
    	virtual void onEnter();
    	virtual void onExit();
    
    private:
    	void buttonCallback(CCObject* pSender);
    
        // 文字内容两边的空白区
        int m_contentPadding;
        int m_contentPaddingTop;
        
        CCObject* m_callbackListener;
        SEL_CallFuncN m_callback;
    
        CC_SYNTHESIZE_RETAIN(Menu*, m__pMenu, MenuButton);
        CC_SYNTHESIZE_RETAIN(Sprite*, m__sfBackGround, SpriteBackGround);
        CC_SYNTHESIZE_RETAIN(Scale9Sprite*, m__s9BackGround, Sprite9BackGround);
        CC_SYNTHESIZE_RETAIN(LabelTTF*, m__ltTitle, LabelTitle);
        CC_SYNTHESIZE_RETAIN(LabelTTF*, m__ltContentText, LabelContentText);
    
    
    };
    
    
    #endif


    PopupLayer.cpp里面的代码

    #include "PopupLayer.h"
    
    PopupLayer::PopupLayer():
    m__pMenu(NULL)
    , m_contentPadding(0)
    , m_contentPaddingTop(0)
    , m_callbackListener(NULL)
    , m_callback(NULL)
    , m__sfBackGround(NULL)
    , m__s9BackGround(NULL)
    , m__ltContentText(NULL)
    , m__ltTitle(NULL)
    {
        
    }
    
    PopupLayer::~PopupLayer(){
        CC_SAFE_RELEASE(m__pMenu);
        CC_SAFE_RELEASE(m__sfBackGround);
        CC_SAFE_RELEASE(m__ltContentText);
        CC_SAFE_RELEASE(m__ltTitle);
        CC_SAFE_RELEASE(m__s9BackGround);
    }
    
    bool PopupLayer::init(){
    	if(!Layer::init()){
    		return false;
    	}
    		this->setContentSize(CCSizeZero);
            
            // 初始化须要的 Menu
            CCMenu* menu = CCMenu::create();
            menu->setPosition(CCPointZero);
            setMenuButton(menu);
            
            setTouchEnabled(true);
    
    	return true;
    }
    
    bool PopupLayer::onTouchBegan(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent){
        //
        CCLog("PopupLayer touch");
        return true;
    }
    
    PopupLayer* PopupLayer::create(const char *backgroundImage){
        PopupLayer* ml = PopupLayer::create();
        ml->setSpriteBackGround(CCSprite::create(backgroundImage));
        ml->setSprite9BackGround(Scale9Sprite::create(backgroundImage));
        return ml;
    }
    
    void PopupLayer::setTitle(const char *title, int fontsize){
        CCLabelTTF* ltfTitle = CCLabelTTF::create(title, "", fontsize);
        setLabelTitle(ltfTitle);
    }
    
    void PopupLayer::setContentText(const char *text, int fontsize, int padding, int paddingTop){
        CCLabelTTF* ltf = CCLabelTTF::create(text, "", fontsize);
        setLabelContentText(ltf);
        m_contentPadding = padding;
        m_contentPaddingTop = paddingTop;
    }
    
    void PopupLayer::setCallbackFunc(cocos2d::CCObject *target, SEL_CallFuncN callfun){
        m_callbackListener = target;
        m_callback = callfun;    
    }
    
    
    bool PopupLayer::addButton(const char *normalImage, const char *selectedImage, const char *title, int tag){
        CCSize winSize = CCDirector::sharedDirector()->getWinSize();
        CCPoint pCenter = ccp(winSize.width / 2, winSize.height / 2);
        
        // 创建图片菜单按钮
        CCMenuItemImage* menuImage = CCMenuItemImage::create(normalImage, selectedImage, this, menu_selector(PopupLayer::buttonCallback));
        menuImage->setTag(tag);
        menuImage->setPosition(pCenter);
        
        // 加入文字说明并设置位置
        CCSize imenu = menuImage->getContentSize();
        CCLabelTTF* ttf = CCLabelTTF::create(title, "", 20);
        ttf->setColor(ccc3(0, 0, 0));
        ttf->setPosition(ccp(imenu.width / 2, imenu.height / 2));
        menuImage->addChild(ttf);
        
        getMenuButton()->addChild(menuImage);
        return true;
    }
    
    void PopupLayer::buttonCallback(cocos2d::CCObject *pSender){
        CCNode* node = dynamic_cast<CCNode*>(pSender);
        CCLog("touch tag: %d", node->getTag());
        if (m_callback && m_callbackListener){
            (m_callbackListener->*m_callback)(node);
        }
        this->removeFromParent();
    }
    
    void PopupLayer::onEnter(){
        CCLayer::onEnter();
        
        CCSize winSize = CCDirector::sharedDirector()->getWinSize();
        CCPoint pCenter = ccp(winSize.width / 2, winSize.height / 2);
        
        CCSize contentSize;
        // 设定好參数,在执行时载入
        if (getContentSize().equals(CCSizeZero)) {
            getSpriteBackGround()->setPosition(ccp(winSize.width / 2, winSize.height / 2));
            this->addChild(getSpriteBackGround(), 0, 0);
            contentSize = getSpriteBackGround()->getTexture()->getContentSize();
        } else {
            Scale9Sprite *background = getSprite9BackGround();
            background->setContentSize(getContentSize());
            background->setPosition(ccp(winSize.width / 2, winSize.height / 2));
            this->addChild(background, 0, 0);
            contentSize = getContentSize();
        }
        
        
        // 加入按钮。并设置其位置
        this->addChild(getMenuButton());
        float btnWidth = contentSize.width / (getMenuButton()->getChildrenCount() + 1);
        
    	Vector<Node*> vecArray = getMenuButton()->getChildren();
        CCObject* pObj = NULL;
        int i = 0;
    	for(auto& e : vecArray){
    		CCNode* node = dynamic_cast<CCNode*>(e);
    		node->setPosition(Point(winSize.width/2 - contentSize.width/2+btnWidth*(i+1),winSize.height/2-contentSize.height/3));
    		i++;
    	}
      /*  CCARRAY_FOREACH(array, pObj){
            CCNode* node = dynamic_cast<CCNode*>(pObj);
            node->setPosition(ccp( winSize.width / 2 - contentSize.width / 2 + btnWidth * (i + 1), winSize.height / 2 - contentSize.height / 3));
            i++;
        }*/
        
        
        // 显示对话框标题
        if (getLabelTitle()){
            getLabelTitle()->setPosition(ccpAdd(pCenter, ccp(0, contentSize.height / 2 - 35.0f)));
            this->addChild(getLabelTitle());
        }
        
        // 显示文本内容
        if (getLabelContentText()){
            CCLabelTTF* ltf = getLabelContentText();
            ltf->setPosition(ccp(winSize.width / 2, winSize.height / 2));
            ltf->setDimensions(CCSizeMake(contentSize.width - m_contentPadding * 2, contentSize.height - m_contentPaddingTop));
            ltf->setHorizontalAlignment(kCCTextAlignmentLeft);
            this->addChild(ltf);
        }
    
        // 弹出效果
        CCAction* popupLayer = CCSequence::create(CCScaleTo::create(0.0, 0.0),
                                                  CCScaleTo::create(0.06, 1.05),
                                                  CCScaleTo::create(0.08, 0.95),
                                                  CCScaleTo::create(0.08, 1.0), NULL);
        this->runAction(popupLayer);
    
    }
    
    void PopupLayer::onExit(){
        
        CCLog("popup on exit.");
        CCLayer::onExit();
    }
    


    在要引用的代码里面加入

    #include "HelloWorldScene.h"
    #include "PopupLayer.h"
    
    USING_NS_CC;
    
    Scene* HelloWorld::createScene()
    {
        // 'scene' is an autorelease object
        auto scene = Scene::create();
        
        // 'layer' is an autorelease object
        auto layer = HelloWorld::create();
    
        // add layer as a child to scene
        scene->addChild(layer);
    
        // return the scene
        return scene;
    }
    
    // on "init" you need to initialize your instance
    bool HelloWorld::init()
    {
        //////////////////////////////
        // 1. super init first
        if ( !Layer::init() )
        {
            return false;
        }
        
         CCSize winSize = CCDirector::sharedDirector()->getWinSize();
            CCPoint pointCenter = ccp(winSize.width / 2, winSize.height / 2);
    
            // 加入背景图片
          /*  CCSprite* background = CCSprite::create("HelloWorld.png");
            background->setPosition(pointCenter);
            background->setScale(1.5f);
            this->addChild(background);    */
            
            //popupLayer();
            
            
            // 加入菜单
            CCMenu* menu = CCMenu::create();
            
            CCMenuItemFont* menuItem = CCMenuItemFont::create("popup", this, menu_selector(HelloWorld::menuCallback));
    		menuItem->setPosition(ccp(winSize.width/2, winSize.height/2));
            menuItem->setColor(ccc3(255, 0, 0));
            menu->addChild(menuItem);
            
    
            menu->setPosition(CCPointZero);
            this->addChild(menu);
       
        
        return true;
    }
    
    
    void HelloWorld::popupLayer(){
        // 定义一个弹出层,传入一张背景图
        PopupLayer* pl = PopupLayer::create("popuplayer/BackGround.png");
        // ContentSize 是可选的设置,可以不设置,假设设置把它当作 9 图缩放
        pl->setContentSize(CCSizeMake(400, 350));
        pl->setTitle("吾名一叶");
        pl->setContentText("娇兰傲梅世人赏,却少幽芬暗里藏。不看百花共争艳,独爱疏樱一枝香。

    ", 20, 60, 250); // 设置回调函数,回调传回一个 CCNode 以获取 tag 推断点击的按钮 // 这仅仅是作为一种封装实现,假设使用 delegate 那就行更灵活的控制參数了 pl->setCallbackFunc(this, callfuncN_selector(HelloWorld::buttonCallback)); // 加入按钮。设置图片,文字,tag 信息 pl->addButton("popuplayer/pop_button.png", "popuplayer/pop_button.png", "确定", 0); pl->addButton("popuplayer/pop_button.png", "popuplayer/pop_button.png", "取消", 1); // 加入到当前层 this->addChild(pl); } void HelloWorld::menuCallback(cocos2d::Object *pSender){ popupLayer(); } void HelloWorld::buttonCallback(cocos2d::Node *pNode){ CCLog("button call back. tag: %d", pNode->getTag()); }



    以下是网上转载的代码,那个里面是cocos2d-x2.x里面的代码,有一些改动

    我们时常须要这么些功能,弹出一个层,给与用户一些提示,这也是一种模态窗体,在没有对当前对话框进行确认的时候,不能继续往下操作。在设计如此功能之时,怎么设计比較合理 ~ 是这篇文章要讨论的问题。一叶 不倾向于提供给一个完整的解决方式。给一堆源代码。而会靠诉你怎样依据你自己的须要去完好它,授人以鱼不如授人以渔 ~

    功能分析

    我们设计一个对话框,对话框上有几个button(个数可定制),当然有个标题,会让别人一眼看出它之功用,里面可以有些具体的提示文字,须要是模态窗体,并且窗体的大小可变。这样可以更好的适应不同的屏幕的大小。当然另一个重要的功能,弹出效果 ~ 尽管从技术角度来说,实现起来并不难。或者说非常easy。但这会以一个非常好的用户体验展示给用户。

    为了使用方面,我将接口设计的尽量简洁,便于使用。例如以下所看到的,至于内部的实现,那就任意了,接口函数是暴露在外面的,给别人使用,所以依据须要首先将它定义好,会让你的实现步骤思路清晰 (本文所用到的源码能够从  这里  获取):

    class PopupLayer: public CCLayer{
    public:
        PopupLayer();
        ~PopupLayer();
    
        virtual bool init();
        CREATE_FUNC(PopupLayer);
    
        // 须要重写触摸注冊函数,又一次给定触摸级别
        virtual void registerWithTouchDispatcher(void);
        // 重写触摸函数,永远返回 true ,屏蔽其他层,达到 “模态” 效果
        bool ccTouchBegan(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent);
    
        // 构架,并设置对话框背景图片
        static PopupLayer* create(const char* backgroundImage);
    
        // 它能够显示标题,而且设定显示文字大小
        void setTitle(const char* title, int fontsize = 20);
        // 文本内容。padding 为文字到对话框两边预留的距离,这是可控的,距上方的距离亦是如此
        void setContentText(const char* text, int fontsize = 20, int padding = 50, int paddintTop = 100);
    
        // 回调函数。当点击button后。我们关闭弹出层的同事,须要一个回调函数,以通知我们点击了哪个button(假设有多个)
        void setCallbackFunc(CCObject* target, SEL_CallFuncN callfun);
    
        // 为了加入button方面。封装了一个函数,传入些必要的參数
        bool addButton(const char* normalImage, const char* selectedImage, const char* title, int tag = 0);
    
        // 为了在显示层时之前的属性生效。选择在 onEnter 里动态展示
        virtual void onEnter();
        virtual void onExit();
    
    };

    从使用方面的角度来说。定义了以上函数,以供外部调用,完毕主要的功能需求。

    当然还有些隐藏的函数,如 setContentSize。

    由此開始我们的下一步设计 ~

    onEnter 动态组建弹出层

    前文提到过。须要的模态窗体大小是可变的,通过 ContentSize 来获取,假设没有设置 ContentSize 。那么採取的方案是。窗体大小与传入图片一样大。反之。将窗体设定为指定大小。

    我们知道有非常多类似于这种属性设置改动等,对于完毕这样一个功能来说,有两种方式。

    其一。 实时设置,实时刷新 ,比方在 static PopupLayer* create(const char* gackgroundImage)  的实现里面,创建一个精灵。并设置好图片。加入到当前层,假设调用了  setContentSize  我们再在此方法获取精灵后去改动这个精灵的大小(非常显然在本文,并没有实现 setContentSize 方法。但并不影响讲解)。

    其二。 保留属性。动态组建 。这样一种实现是在 static PopupLayer* create(const char* gackgroundImage)  方法内部,仅仅保存图片的名称,而  setContentSize  也能够仅仅专注于自己的工作就可以。最后在一个适当的运行时期,依据以上两个參数。动态创建符合需求的精灵。而这个操作在 onEnter 里尤为合适。

    再以一个当前用到的样例,来说明  实时刷新  与  动态组建  的差别。

    看到定义中有一个  addButton  的方法,它是为了能够在当前对话框中加入一个或者几个button,而加入几个?当然并不确定,但确定的是,它们的位置会随着button个数的不同而不同,假设一个button,将居中显示(一分为二)。假设两个(三等份距离),假设是实时刷新。我们在每一次  addButton  方法里面创建一个新的button,还须要设置正确的位置。当然在设置新位置的时候,你须要去推断是否已经存在button。还须要改动q前面button的位置。能够预见,每加入一次,都须要去实时刷新之前设置过的值,假设代码逻辑简单还好。假设逻辑很复杂,依赖属性之多。那么那将不好控制。假设使用  动态组建 。在  addButton  方面里面我们仅仅须要用一个集合(类似机制)来保存全部的button信息。仅此而已,然后在 onEnter 中。读取这些信息,以实时加入button至界面之中。而在执行到这里之时。属性基本已经确定了(这里是button个数)。仅仅需计算一次各button的位置,这种逻辑处理就相当清晰了 ~

    能够说动态组建就一定比实时刷新要好么?当然不是。

     一个採用实时刷新的样例: 在 Cocos2d-x 的 CCControl 的框架中,使用了实时刷新的解决方式。能够在非常多地方看到类似  needsLayout()  这种操作,在设定一个控件的属性之后,须要依据属性更新控件的布局等。

    对于 实时刷新 与 动态组建 这两种方式,须要依据实际情况来选择。以简化我们的开发,而在文本中,基本是以动态组建的方式设计,由于在弹出层执行之时。全部的属性就已经确定。它没有必要再去依据属性实时刷新。

    弹出层的触摸优先级。操作与显示相一致

    -128  是一个有意义的数字,它是 CCMenu 的默认触摸级别,假设我们不使用自带的菜单项,那么对于触摸级别的问题就非常优点理了,随便一个略微大一点的值,就可以。

    可是你须要自己写button处理的实现。当然使用 CCMenu 也是有优点的,它封装了非常好用的点击操作。为了简化开发,这里就基于以 CCMenu 作为对话框button的操作实现。那么我们的 弹出层 触摸级别改设置为多少?

    在我们设定触摸级别时。请记住一句话, 操作与显示相一致 。

    此话何意?如今设想这样一种情况,我们为了屏蔽弹出层以外全部的层的操作,而将弹出层级别置为 -129 。这样便保证了它是模态的了(一般而言。除了 CCMenu 的级别,用户自己定义也无需这么大),可是假设当前弹出层上方还有其他的层(也能够是弹出层的父节点上方有其他层。如多层的 UI 设计)。而且其上也有 CCMenu button。那么就出现了显示在 弹出层上放层中的 CCMenu button不能点击,这不科学!

    实际。在弹出层的 CCMenu 也不能点击,仅仅是我们能够通过将弹出层的触摸消息传递给层中的 CCMenu 解决。所以设置为一味的追求最大的触摸优先级。并不可取。它不能非常好的做到  操作与显示相一致 。而优先级小于 CCMenu 并不能屏蔽下方的其他 CCMenu 操作。所以对于弹出层本身,它设置为 -128 是合理的,对于相同级别的这些元素来说(弹出层和CCMenu),能够做到。显示在最上方的优先处理。假设在弹出层上方还有层,是能够点击的,为什么不呢!

    而我们要做的是。通过逻辑控制,让弹出层节点。最后加入到场景的最上方。

    对于  操作与显示相一致  的一个解决方式。能够參考一叶的另两篇文章, 多层 UI 触摸事件的轻量级设计 。和  CCScrollView 实现帮助界面、关卡选择 。当然那里并没实用到 CCMenu。而是独立创建了一套规则。

    回调函数的实现方案

    因为我们使用了 CCMenu 作为button,所以全然能够将 CCMenu 的回调函数,当作參数传入进来,这样处理确实非常easy,可是还有一个问题,我门须要在事件处理完之后。关闭当前层。那这就不能只如此了。须要进一步封装。将弹出层的button回调函数设置为内部实现,然后在 回调给它的上层,之后关闭对话框(关闭的操作由对话框层来完毕)。对于回调一般有两种方式。一种是  delegate  回调。这须要定义接口。由上层,继承实现接口,并把自己当作參数。传入弹出层,由弹出层调用 delegate 的接口方法实现,在 Cocos2d-x 里面非常多地方用到此方式。而还有一种则是 函数绑定,就像 CCMenu 那样的绑定函数。

    在这里。一叶选择了后者,假设当前弹出层固定一个或者两个button,那么我将使用 delegate 来实现函数回调。它会使回调步骤更为清晰,可是,这里设计的是button个数可变。功能也不尽同样,使用回调函数,绑定 CCNode 參数,以其 tag 标示。点击的是哪个button,当然这里也并非说使用那种方式是绝对的好坏。

    delegate 对參数传递来说,更为严谨。 void setCallbackFunc(CCObject* target, SEL_CallFuncN callfun);  的定义是类似 CCMenu 的回调机制,一个 CCNode 作为參数,其 tag 用以标示当前点击的是哪个button。

    弹出层的调用

    void Popup::popupLayer(){
        // 定义一个弹出层,传入一张背景图
        PopupLayer* pl = PopupLayer::create("popuplayer/BackGround.png");
        // ContentSize 是可选的设置,可以不设置,假设设置把它当作 9 图缩放
        pl->setContentSize(CCSizeMake(400, 350));
        pl->setTitle("吾名一叶");
        pl->setContentText("娇兰傲梅世人赏,却少幽芬暗里藏。

    不看百花共争艳。独爱疏樱一枝香。", 20, 60, 250); // 设置回调函数,回调传回一个 CCNode 以获取 tag 推断点击的按钮 // 这仅仅是作为一种封装实现。假设使用 delegate 那就行更灵活的控制參数了 pl->setCallbackFunc(this, callfuncN_selector(Popup::buttonCallback)); // 加入按钮,设置图片,文字,tag 信息 pl->addButton("popuplayer/pop_button.png", "popuplayer/pop_button.png", "确定", 0); pl->addButton("popuplayer/pop_button.png", "popuplayer/pop_button.png", "取消", 1); // 加入到当前层 this->addChild(pl); } void Popup::buttonCallback(cocos2d::CCNode *pNode){ // 打印 tag 0, 确定,1 ,取消 CCLog("button call back. tag: %d", pNode->getTag()); } // 弹出效果 关键代码,当前层直运行这个动作 CCAction* popupLayer = CCSequence::create(CCScaleTo::create(0.0, 0.0), CCScaleTo::create(0.06, 1.05), CCScaleTo::create(0.08, 0.95), CCScaleTo::create(0.08, 1.0), NULL);

    这里一张截图,当中 popup button是个 CCMenu,弹出层中两个button也是 CCMenu。而层本身的触摸优先级别也是 -128 ,都是同级,那就依我所言,操作与显示相一致,唯一要注意的是逻辑的控制,什么时候弹出层。由哪个节点弹出层(一般由场景基层来负责)。以保证它显示在最上方。

    Cocos2d-x 弹出对话框的设计与实现

    通过以上的讨论实践。完毕了对话框的基本模型,它实现了下面功能:

    • 一个能够弹出的对话框实现
    • 模态窗体的实现(须要逻辑的控制)
    • 多button的支持,位置自适应,提供回调函数
    • 提供标题和内容设置
    • 支持  九图  。控制适应弹出框大小

    当然还有很多其他并没有照应到的功能,或者不完好的地方。这就须要用户自己扩展,定制了,如,这样一个层,至少应该是单例的。不论什么时候仅仅应该存在一个,能够用单例模式实现,对于弹出层的内容方面,这里仅仅有标题和内容。而且标题位置固定。button的位置还能够更灵活的设置等。

     

    版权声明:本文博客原创文章,博客,未经同意,不得转载。

  • 相关阅读:
    08day 操作命令以及目录结构
    换工作
    json转为字典
    快速排序
    冒泡排序
    python函数-生成器
    关键字global
    函数的定义和参数调用
    count()函数与center()函数
    python字符串常用函数:strip()
  • 原文地址:https://www.cnblogs.com/bhlsheji/p/4753882.html
Copyright © 2011-2022 走看看