在我的项目中,我想让用户触摸屏幕,当他移动时会画一条线。
我还想确保用户不会与他之前绘制的任何现有线条相交(包括同一线条本身)。
我四处寻找线相交算法或函数,但它们太复杂,而且性能也不好。于是,我想到了另一种方法。通过设置背景和线条的颜色不同,如果我可以读取当前触摸点的颜色,那么我可以将其与线条颜色进行比较,看看是否发生了交叉。
我尝试使用 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/