2012-06-05 101 views
1

我正在使用Cocos2d來拖動sprite,並嘗試添加邊框(如果選擇了sprite)。我可以顯示我的白色背景,但我的邊界證明特別困難。我有這樣的代碼:CCLayer周圍的邊框

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; 

我試過各種咒語,但似乎沒有顯示邊框。我只需要一個矩形的黑色邊框,在我的圖層上的其他所有元素的背面都填充了白色。

回答

5

您可以創建自己的類,它將包含您的精靈並在需要時繪製邊界。要繪製邊框覆蓋類的draw()方法

-(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); 
    } 

} 

你在這個方法來繪製將ZORDER 0繪製,所以,就看你的邊界,與ZORDER添加你的精靈-1。

+0

非常好,那正是我需要的。 m_needDrawRect是你用來控制筆畫是否可見的。 – Echilon

+0

是的,這段代碼剛從我的課程複製過來=) – Morion