cocos2d之,创建一个有背景颜色的layer

创建一个带有背景颜色的Layer,我们需要用到CCLayer的一个派生类CCLayerColor,看如下代码:

    CCSize s = CCDirector::sharedDirector()->getWinSize();
    CCLayer *layer = CCLayerColor::create(ccc4(0xff, 0x00, 0x00, 0x80), 200, 200);
    layer->ignoreAnchorPointForPosition(false);
    layer->setPosition(s.width / 2, s.height / 2);
    this->addChild(layer, 1, layer->getTag());

在这里用到了ccc4这个函数,我们看函数原型:

static inline ccColor4B
ccc4(const GLubyte r, const GLubyte g, const GLubyte b, const GLubyte o)

ccColor4B是一个结构体:

typedef struct _ccColor4B
{
    GLubyte r;
    GLubyte g;
    GLubyte b;
    GLubyte a;
} ccColor4B;

ccColor4B是个结构体,由r、g、b、a四个参数组成(a是透明度,即alpha),但和ccColor3B不同的是,它们都是浮点数,取值范围为0~1(1就相当于GLubyte的255)。squareColors_的作用是充当openGL绘制颜色的参数,因为GL的API需要浮点数,所以ccColor3B不能直接用于绘制,当层的颜色发生变化时,squareColors_会根据color_和opacity自动换算。


下面还可以通过ccBlendFunc来改变背景层的颜色:

    CCLayerColor *layer1 = CCLayerColor::create(ccc4(255, 0, 0, 100), 300, 200);
    CCLayerColor *layer2 = CCLayerColor::create(ccc4(255,255,0,110), 100, 100);
    
    addChild(layer1);
    layer1->addChild(layer2);
    layer1->ignoreAnchorPointForPosition(false);
    layer1->setAnchorPoint(ccp(0.5, 0.5));
    layer1->setPosition(ccp(250, 220));
    ccBlendFunc bf = {GL_ONE_MINUS_DST_COLOR, GL_ZERO}; //这里定义背景的颜色
    layer1->setBlendFunc(bf);



你可能感兴趣的:(cocos2d之,创建一个有背景颜色的layer)