cocos2d创建带有背景颜色的layer

前端之家收集整理的这篇文章主要介绍了cocos2d创建带有背景颜色的layer前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

这次笔者创建了一个带有背景颜色的layer,同时生成了一个Sprite和一个CCLabelTTf,字体显示在Sprite的中心所在。

代码如下:

GameScene.h

#ifndef __GAMASCENE__H
#define __GAMASCENE__H

#include "cocos2d.h"
class CGameScene : public cocos2d::CCLayerColor
{
public:
    // Here's a difference. Method 'init' in cocos2d-x returns bool,instead of returning 'id' in cocos2d-iphone
    virtual bool init();

    // there's no 'id' in cpp,so we recommend returning the class instance pointer
    static cocos2d::CCScene* scene();

    // a selector callback
   // void menuCloseCallback(CCObject* pSender);

    // implement the "static node()" method manually
    CREATE_FUNC(CGameScene);
};

#endif // __HELLOWORLD_SCENE_H__

GameScene.cpp文件内容如下:
#include "GameScene.h"
#include "AppMacros.h"
USING_NS_CC;

CCScene* CGameScene::scene() {

	// 'scene' is an autorelease object
	CCScene *scene = CCScene::create();
	// 'layer' is an autorelease object
	CGameScene *layer = CGameScene::create();

	//默示获得视口(可视区域)的大小
	CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
	//表示可视区域的起点坐标,这在处理相对位置的时候非常有用,确保节点在不同分辨率下的位置一致
	CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();
	//将该层设置为屏幕大小
	layer->setContentSize(CCSize(visibleSize.width,visibleSize.height));
	//将该层的起点设置为屏幕原点
	layer->setPosition(origin.x,origin.y);
	// add layer as a child to scene
	scene->addChild(layer);
	// return the scene
	return scene;
}

bool CGameScene::init() {
	 if (!CCLayerColor::initWithColor(ccc4(0xff,0xff,0xff),200,200))
	 {
		 return false;
	 }

	CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize(); //默示获得视口(可视区域)的大小
	CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin(); //表示可视区域的起点坐标,确保节点在不同分辨率下的位置一致

	for (int i = 0; i < 20; i++) {
		CCSprite* pSprite = ::CCSprite::create("qiu1.png");
		pSprite->setScale(0.25); //	缩放为原来的1/2
		pSprite->setPosition(
				ccp(visibleSize.width / 2 + origin.x+i*60,visibleSize.height / 2 + origin.y)); //确保该图在屏幕中心
		CCLabelTTF*pLabel = CCLabelTTF::create("4","Arial",TITLE_FONT_SIZE);
		CCSize pSize = pSprite->getContentSize();
		CCPoint pPoint = pSprite->getPosition();
		pLabel->setScale(4);
		pLabel->setPosition(ccp(pSize.width / 2,pSize.height / 2)); //如果想要子节点在父节点的中心,则只是需要获得父节点的尺寸,子节点的位置是父节点的中心即可
		int a = pSprite->getZOrder();
		pLabel->setZOrder(a + 1);
		//设置颜色为粉红
		pLabel->setColor(ccc3(255,192,203));
		pSprite->addChild(pLabel);
		this->addChild(pSprite,0);
	}

	return true;
}

这样就完成了一个背景层颜色设置。以及两个父子关系的CCNode的相对位置确定 原文链接:https://www.f2er.com/cocos2dx/343254.html

猜你在找的Cocos2d-x相关文章