从一种颜色到另一种颜色绘制SKShapeNode线颜色渐变

时间:2016-11-05 15:49:19

标签: ios objective-c sprite-kit

我正在为iPad和iOS 10编写应用程序。 我正在使用Objective-C和SpriteKit。

我需要绘制一条以一种颜色开始并以另一种颜色结束的线条(例如红色到绿色)。

这是我的Objective-C代码:

CGPoint points[2];
points[0] = CGPointMake(100, 100);
points[1] = CGPointMake(160, 110);

SKShapeNode *line1=[SKShapeNode shapeNodeWithPoints:points count:2];
line1.lineWidth = 2.0;
line1.zPosition = -1;
line1.name=@"line";
SKShader *myShader=[SKShader shaderWithFileNamed:@"shader1.fsh"];
line1.strokeShader=myShader;
[self addChild:line1];

这是着色器:

void main(){

float length = u_path_length;
float distance = v_path_distance;


gl_FragColor = vec4(1.0*(1-(distance/length)), 1.0*(distance/length), 0., 1.);
}

当我运行应用程序时,我收到错误(与Metal相关): 断言失败'在索引1处为u_path_length [0]丢失缓冲区绑定。'

看起来u_path_length和v_path_distance在iOS 10中不起作用。

你能帮忙解决这个问题吗? 或者你能为这个问题建议一个不同的解决方案吗?

1 个答案:

答案 0 :(得分:1)

如果我在Info.plist文件中添加了bool值为YES的PrefersOpenGL键,则错误(与Metal相关)消失。 当然这意味着我的应用程序不会使用Metal。 我想这是iOS 10中的一个错误。

我遇到了另一个问题:v_path_distance按预期工作,但u_path_length没有。 u_path_length总是= 0。

要解决这个问题,我必须修改我的代码。

这是我的Objective-C代码:

CGPoint points[2]; 
points[0] = CGPointMake(100, 100); 
points[1] =  CGPointMake(160, 110);

SKShapeNode *line1=[SKShapeNode shapeNodeWithPoints:points count:2];
line1.lineWidth = 2.0; 
line1.zPosition = -1; 
line1.name=@"line"; 
SKShader *myShader=[SKShader shaderWithFileNamed:@"shader1.fsh"];   
float my_length=hypotf(points[1].x-points[0].x, points[1].y-points[0].y); 
myShader.uniforms=@[[SKUniform uniformWithName:@"u_my_length" float:my_length]];
line1.strokeShader=myShader; 
[self addChild:line1];

这是着色器:

void main(){    

gl_FragColor=vec4(1.0*(1.0-(v_path_distance/u_my_length)),1.0*(v_path_distance/u_my_length),0.,1.0);

}
相关问题