如何用Cocos2d-iPhone绘制线条?

最近,我在尝试使用cocos2d,设定了一个场景,里面有一个背景sprite和一个layer。我想用drawLine在layer上进行绘制操作:

@implementation MyLayer
-(id)init{
    self = [super init];
    if(self != nil){
        glColor4f(0.8, 1.0, 0.76, 1.0);  
        glLineWidth(2.0f);
        CocosNode *line = drawLine(10.0f, 100.0f,400.0f,27.0f);
        [self addChild:line z:1];
    }
    return self;
}
@end

但这样会出现“void value not ignored as it ought to be”这样的问题,我也尝试过如下操作,

-(id)init{
    self = [super init];
    if(self != nil){
        glColor4f(0.8, 1.0, 0.76, 1.0);  
        glLineWidth(2.0f);
        drawLine(10.0f, 100.0f,400.0f,27.0f);
    }
    return self;
}

虽然没有给出error的提示,但是也不能正常绘制。我觉得应该是哪些基础问题没弄清楚,大家能帮我解答下吗?

原问题:How to draw a line with Cocos2d-iPhone

阅读 3.1k
1 个回答

答:Travis
(最佳答案)
用cocos2d中的drawPrimitivesTest.m可以解决这个问题:

- (void)draw {
  // ...

  // draw a simple line
  // The default state is:
  // Line Width: 1
  // color: 255,255,255,255 (white, non-transparent)
  // Anti-Aliased
  glEnable(GL_LINE_SMOOTH);
  ccDrawLine( ccp(0, 0), ccp(s.width, s.height) );

  // ...
}

答:Tim Sullivan
我用如下代码解决这个问题:

@implementation GameLayer
-(id)init{
    self = [super init];
    if(self != nil){
        // init stuff here      
    }
    return self;
}

// You have to over-ride this method
-(void)draw{
    glColor4f(0.8, 1.0, 0.76, 1.0);  
    glLineWidth(2.0f);
    drawLine(10,100,50,79);
}    
@end

我估计这种方法适用于任何框架。


答:huyleit
你也可以使用CCRibbon类别中的texture进行绘制,例如:
首先你应该设定CCRibbon中的width , image , length , color和fade parameters

ccColor4B myColor = ccc4(255, 255, 255, 150);

CCRibbon *ribbon = [CCRibbon ribbonWithWidth:10 image:@"green.png" length:10.0 color:myColor fade:0.7f];

Then we add it as a child:
然后将它添加为一个子项:

[self addChild:ribbon z:8];

If you run the application now you will not see anything because you didn’t add any points yet to the CCRibbon so lets add 2 points
如果运行应用,什么都不会看到,因为你没有为CCRibbon添加任何内容,所以应该添加:

[ribbon addPointAt:ccp(10,10) width:10];

[ribbon addPointAt:ccp(15,15) width:10];

你不可以消除任何单个的point,但是可以将CCRibbon从主项(parent)中删除。

[self removeChild:ribbon cleanup:YES];

下面是源码下载地址:
http://www.ccsprite.com/cocos2d/using-ccribbon-example.html

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进