ios - cocos2d/IOS中获取背景颜色

标签 ios cocos2d-iphone

在我的项目中,我想让用户触摸屏幕,当他移动时会画一条线。

我还想确保用户不会与他之前绘制的任何现有线条相交(包括同一线条本身)。

我四处寻找线相交算法或函数,但它们太复杂,而且性能也不好。于是,我想到了另一种方法。通过设置背景和线条的颜色不同,如果我可以读取当前触摸点的颜色,那么我可以将其与线条颜色进行比较,看看是否发生了交叉。

我尝试使用 glReadPixel 方法,但它为所有未设置为背景或线条的触摸点返回绿色。我的背景是默认颜色(黑色),线条是默认白色。所有线条都绘制在同一层中。我没有将背景绘制为单独的图层。仅使用默认值。

    -(void) ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    CCLOG(@"touch moved");
    UITouch* touch = [touches anyObject];
    CGPoint currentTouchPoint = [touch locationInView:[touch view]];
    CGPoint lastTouchPoint = [touch previousLocationInView:[touch view]];

    currentTouchPoint = [[CCDirector sharedDirector] convertToGL:currentTouchPoint];
    lastTouchPoint = [[CCDirector sharedDirector] convertToGL:lastTouchPoint];

    CCRenderTexture* renderTexture = [CCRenderTexture renderTextureWithWidth:1 height:1];
    [renderTexture begin];
    [self visit];
    Byte pixelColors[4];
    glReadPixels(currentTouchPoint.x, currentTouchPoint.y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &pixelColors[0]);
    [renderTexture end];
    CCLOG(@"pixel color: %u, %u, %u", pixelColors[0], pixelColors[1], pixelColors[2]); 


    CCLOG(@"last a=%.0f, b=%.0f", lastTouchPoint.x, lastTouchPoint.y);
    CCLOG(@"Current x=%.0f, y=%.0f",currentTouchPoint.x, currentTouchPoint.y);
    [touchPoints addObject:NSStringFromCGPoint(currentTouchPoint)];
    [touchPoints addObject:NSStringFromCGPoint(lastTouchPoint)];
}

-(void)draw{
    CGPoint start;
    CGPoint end;
    glLineWidth(4.0f);
    for (int i=0; i<[touchPoints count]; i=i+2) {
        start = CGPointFromString([touchPoints objectAtIndex:i]);
        end = CGPointFromString([touchPoints objectAtIndex:i+1]);
        ccDrawLine(start, end);
    }
}

最佳答案

您只能在绘制或访问方法中使用 OpenGL 方法(此处为 glReadPixels)。这很可能就是你一直变绿的原因。

在渲染纹理的开始/结束方法中,您只能访问渲染纹理,而不能访问帧缓冲区。

关于ios - cocos2d/IOS中获取背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15450855/

相关文章:

ios - 实例变量会限制性能吗?一个类应该有两个目的吗?

math - Cocos2D/Math - 干净的角度转换

iphone - 使用 AVFoundation 在自定义播放器中播放 youtube 视频

iphone - 检测每秒音频文件的幅度?

iphone - 如何在 iPhone 5 中获得黑边

iphone - Cocos2d & Box2d 动态光照和阴影

ios - 如何在Cocos2D iPhone中拍摄屏幕截图?

ios - 无法访问 Sprite 的用户数据属性

android - Google 的 G Suite 应用程序如何共享数据?

ios - 重新排序时无法从当前位置拖动 UITableViewCell