将由贝塞尔曲线路径形成的形状转换为SKNode,同时保持颜色和渐变等属性

时间:2014-03-08 07:03:41

标签: objective-c core-graphics sprite-kit

我知道SKShapeNode可以将其形状设置为bezier路径,但有没有办法将所有颜色的bezier路径“原样”传输到SKNode中?

例如,我有一个形状的代码:

//// General Declarations
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = UIGraphicsGetCurrentContext();

//// Color Declarations
UIColor* fillColor = [UIColor colorWithRed: 0.333 green: 0.333 blue: 0.333 alpha: 1];
UIColor* strokeColor = [UIColor colorWithRed: 0 green: 0 blue: 0 alpha: 1];

//// Gradient Declarations
NSArray* gradientColors = [NSArray arrayWithObjects: 
    (id)fillColor.CGColor, 
    (id)strokeColor.CGColor, nil];
CGFloat gradientLocations[] = {0, 1};
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)gradientColors, gradientLocations);

//// Bezier Drawing
UIBezierPath* bezierPath = [UIBezierPath bezierPath];
[bezierPath moveToPoint: CGPointMake(-0.5, 51.54)];
[bezierPath addLineToPoint: CGPointMake(209.94, 51.54)];
[bezierPath addLineToPoint: CGPointMake(198.28, 88.97)];
[bezierPath addLineToPoint: CGPointMake(357.67, 90.5)];
[bezierPath addLineToPoint: CGPointMake(358.25, 51.54)];
[bezierPath addLineToPoint: CGPointMake(480.5, 56.92)];
[bezierPath addLineToPoint: CGPointMake(480.5, 0.5)];
[bezierPath addLineToPoint: CGPointMake(-0.5, 0.5)];
[bezierPath addLineToPoint: CGPointMake(-0.5, 51.54)];
[bezierPath closePath];
CGContextSaveGState(context);
[bezierPath addClip];
CGContextDrawLinearGradient(context, gradient, CGPointMake(240, 90.5), CGPointMake(240, 0.5), 0);
CGContextRestoreGState(context);
[strokeColor setStroke];
bezierPath.lineWidth = 1;
[bezierPath stroke];


//// Cleanup
CGGradientRelease(gradient);
CGColorSpaceRelease(colorSpace);

在屏幕上绘制时,此代码的形状如下所示:

Shape

有没有办法可以在保持颜色和渐变的同时将此形状转换为SKNode?谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

SKShapeNode的第一个是SKNode的子类,因此您可以使用SKSode执行所有可以使用SKShapeNode执行的操作。

SKNode不是“可显示的”。它是其他节点的持有者,可以像SKShapeNode和SKSpriteNode一样呈现。如果你需要SKShapeNode中的SKSpriteNode,你可以使用SKView的textureFromNode:,从而获得一个可以用来初始化SKSpriteNode的SKTexture。