Border around CCLayer

2019-08-01 06:57发布

I'm using Cocos2d to drag sprite around, and trying to add a border if a sprite is selected. I can get my white background to display, but my border is proving particularly difficult. I have this code:

if(self.selectedSprite)
    self.selectedSprite = nil;

CCLayerColor *selectedLayer = [[CCLayerColor alloc] init];
//    CCSprite *backgroundSprite = [CCSprite spriteWithFile:@"white_1x1.gif" rect:CGRectMake(2,2,self.boundingBox.size.width-4,self.boundingBox.size.height-4)];
CCSprite *backgroundSprite = [CCSprite spriteWithFile:@"white_1x1.gif" rect:CGRectMake(0,0,self.boundingBox.size.width,self.boundingBox.size.height)];
[backgroundSprite setContentSize:CGSizeMake(self.contentSize.width-4, self.contentSize.height-4)];
backgroundSprite.anchorPoint = ccp(0,0);

CCRenderTexture* rt = [CCRenderTexture renderTextureWithWidth:backgroundSprite.texture.contentSize.width + 2  height:backgroundSprite.texture.contentSize.height+2];

[backgroundSprite setFlipY:YES];
[backgroundSprite setColor:ccc3(0,0,0)];
ccBlendFunc originalBlendFunc = [backgroundSprite blendFunc];
[backgroundSprite setBlendFunc:(ccBlendFunc) { GL_SRC_ALPHA, GL_ONE }];

CGPoint bottomLeft = ccp(backgroundSprite.texture.contentSize.width * backgroundSprite.anchorPoint.x + 1, backgroundSprite.texture.contentSize.height * backgroundSprite.anchorPoint.y + 1);
CGPoint position = ccpSub([backgroundSprite position], ccp(-backgroundSprite.contentSize.width / 2.0f, -backgroundSprite.contentSize.height / 2.0f));

[rt begin];

for (int i=0; i<360; i++) // you should optimize that for your needs
{
    [backgroundSprite setPosition:ccp(bottomLeft.x + sin(CC_DEGREES_TO_RADIANS(i))*1, bottomLeft.y + cos(CC_DEGREES_TO_RADIANS(i))*1)];
    [backgroundSprite visit];
}

[backgroundSprite setPosition:bottomLeft];
[backgroundSprite setBlendFunc:originalBlendFunc];
[backgroundSprite setColor:ccc3(255,255,255)];
[backgroundSprite visit];

[rt end];

[rt setPosition:position];

[selectedLayer addChild:rt];
[selectedLayer addChild:backgroundSprite];
self.selectedSprite = selectedLayer;

I've tried various incantations, but nothing seems to show a border. I just need a rectangular black border which is filled with white at the back of everything else on my layer.

1条回答
相关推荐>>
2楼-- · 2019-08-01 07:18

You can create your own class, that will contain your sprite and draw border over it if is needed. To draw border override draw() method of your class

-(void) draw
{
    if( m_needDrawRect == YES )
    {
        CGSize selfSize = [self contentSize];
        float selfHeight = selfSize.height;
        float selfWidth = selfSize.width;
        CGPoint vertices[4] = {ccp(0.f, 0.f), ccp(0.f, selfHeight), ccp(selfWidth, selfHeight), ccp(selfWidth, 0.f)};
        ccDrawPoly(vertices, 4, YES);
    }

}

all you draw in this method will be drawn with zOrder 0, so, to see your border, add your sprite with zOrder -1.

查看更多
登录 后发表回答