UI开发之控件类-CCControlButton

在应用的开发中,无论是Android操作系统还是iOS操作系统,其开发框架都提供了控件,包括按键、拖动滑块等,这样提高了开发效率。对于游戏的开发,UI的开发同样需要控件来提高开发效率。对Cocos2D-x来说,从2.0版本开始提供了很多控件类来帮助我们更好地开发UI。

bool HelloWorld::init()
{
    bool bRet = false;
    do 
    {
      
        CC_BREAK_IF(! CCLayer::init());

		//预加载声音资源
		CocosDenshion::SimpleAudioEngine::sharedEngine()->preloadBackgroundMusic("backgroundMusic.mp3");

		CCLabelTTF * title = CCLabelTTF::create("music","Arial",32);
		//可以设置一些title的颜色
		//title->setColor(ccGREEN);

		//创建一张九妹图片,一会向button中传入
		CCScale9Sprite * buttonNormal = CCScale9Sprite::create("buttonBackground.png");

		CCControlButton * button = CCControlButton::create(title,buttonNormal);
		//这么设置的话就没有背景图片了
		//CCControlButton * button = CCControlButton::create("close music","Arial",32);

		//修改button的背景图片
		CCScale9Sprite * spriteSelected = CCScale9Sprite::create("buttonHighlighted.png");
		button->setBackgroundSpriteForState(spriteSelected,CCControlStateSelected);

		//修改title的颜色
		button->setTitleColorForState(ccGREEN, CCControlStateHighlighted);
		
		//为按钮添加事件监听
		button->addTargetWithActionForControlEvents(this,cccontrol_selector(HelloWorld::touchDown),
			CCControlEventTouchUpInside);

		button->setPosition(ccp(240,160));
		this->addChild(button);

        bRet = true;
    } while (0);

    return bRet;
}

void HelloWorld::touchDown(CCObject * pSender,CCControlEvent  controlEvent)
{
	CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic("backgroundMusic.mp3");
}

UI开发之控件类-CCControlButton_第1张图片

你可能感兴趣的:(cocos2d-x,cocos2d-x,游戏)