Draw Rectangle/ Circle and Triangle in Spritekit with Two Colors. . .

Programmer picture Programmer · Sep 30, 2013 · Viewed 14.1k times · Source

I can draw Rectangle using simple SKSpriteNode. But i can not draw other types of drawings in it like Triangle, Circle etc with TWO SPLIT COLORS. Someone suggested to go with CGPath. But i am newbie and dont know to draw such type of complex things . Please can anyone illustrate simple way to go with these drawings with MULTICOLOR in SPRITEKIT. Mean their upper part is one color and lower part in 2nd color. More concise to say that Shape is divided into two colors whether that is star, rectangle, triangle or else. Any Help will be greatly appreciated.

Thanks .

Answer

Greg picture Greg · Sep 30, 2013

You can use SKShapeNode to draw shapes in sprite kit, but each SKShapeNode is limited to one line color (strokeColor) and one fill color.

However, you can create a custom SKNode subclass that contains two SKShapeNodes as children, each with different strokeColors/fillColors.

Something like this will work for a custom SKNode that draws a square with left and top red, right and bottom green:

- (id) init {
    if (self = [super init]) {
        SKShapeNode* topLeft = [SKShapeNode node];
        UIBezierPath* topLeftBezierPath = [[UIBezierPath alloc] init];
        [topLeftBezierPath moveToPoint:CGPointMake(0.0, 0.0)];
        [topLeftBezierPath addLineToPoint:CGPointMake(0.0, 100.0)];
        [topLeftBezierPath addLineToPoint:CGPointMake(100.0, 100.0)];
        topLeft.path = topLeftBezierPath.CGPath;
        topLeft.lineWidth = 10.0;
        topLeft.strokeColor = [UIColor redColor];
        topLeft.antialiased = NO;
        [self addChild:topLeft];

        SKShapeNode* bottomRight = [SKShapeNode node];
        UIBezierPath* bottomRightBezierPath = [[UIBezierPath alloc] init];
        [bottomRightBezierPath moveToPoint:CGPointMake(0.0, 0.0)];
        [bottomRightBezierPath addLineToPoint:CGPointMake(100.0, 0.0)];
        [bottomRightBezierPath addLineToPoint:CGPointMake(100.0, 100.0)];
        bottomRight.path = bottomRightBezierPath.CGPath;
        bottomRight.lineWidth = 10.0;
        bottomRight.strokeColor = [UIColor greenColor];
        bottomRight.antialiased = NO;
        [self addChild:bottomRight];
    }
    return self;
}