Shapes in sprite kit - objective-c

How do you make a circle or another shape in sprite kit I have seen some that use CGPath but i haven't really ever used CGPath ever . I was able to make a square with SKSpritenode but I can't seem to make triangles or circles.

This creates an SKShapeNode and sets its path property to a circle path with radius 16.
SKShapeNode *shape = [SKShapeNode node];
CGRect rect = CGRectMake(0, 0, 32, 32);
shape.path = [self circleInRect:rect];
shape.strokeColor = [SKColor greenColor];
shape.fillColor = [SKColor redColor];
shape.position = CGPointMake(100,100);
[self addChild:shape];
This method returns a CGPath object initialized with a oval path
- (CGPathRef) circleInRect:(CGRect)rect
{
// Adjust position so path is centered in shape
CGRect adjustedRect = CGRectMake(rect.origin.x-rect.size.width/2, rect.origin.y-rect.size.height/2, rect.size.width, rect.size.height);
UIBezierPath *bezierPath = [UIBezierPath bezierPathWithOvalInRect:adjustedRect];
return bezierPath.CGPath;
}
Here's a triangle path...
- (CGPathRef) triangleInRect:(CGRect)rect
{
CGFloat offsetX = CGRectGetMidX(rect);
CGFloat offsetY = CGRectGetMidY(rect);
UIBezierPath* bezierPath = [UIBezierPath bezierPath];
[bezierPath moveToPoint: CGPointMake(offsetX, 0)];
[bezierPath addLineToPoint: CGPointMake(-offsetX, offsetY)];
[bezierPath addLineToPoint: CGPointMake(-offsetX, -offsetY)];
[bezierPath closePath];
return bezierPath.CGPath;
}

Code snippet to create Triangle using Sprite Kit
SKShapeNode* leftContainer = [SKShapeNode node];
leftContainer.position = CGPointMake(CGRectGetMidX(self.frame),
CGRectGetMidY(self.frame));
CGMutablePathRef pathLeftContainer = CGPathCreateMutable();
// Move to position and Draws line to form a triangle
CGPathMoveToPoint(pathLeftContainer, NULL, 60, 100);
CGPathAddLineToPoint(pathLeftContainer, 0, 120, 160);
CGPathAddLineToPoint(pathLeftContainer, 0,180,100);
CGPathAddLineToPoint(pathLeftContainer, 0,60,100);
[leftContainer setPath:pathLeftContainer];
leftContainer.lineWidth = 10.0;
leftContainer.strokeColor = [UIColor redColor];
leftContainer.physicsBody = [SKPhysicsBody bodyWithEdgeChainFromPath:leftContainer.path];
leftContainer.physicsBody.dynamic = FALSE;
[leftContainer.physicsBody setAllowsRotation:FALSE];
[self addChild:leftContainer];
CGPathRelease(pathLeftContainer);
Code snippet to create Circle using Sprite Kit
SKShapeNode* leftContainer = [SKShapeNode node];
leftContainer.position = CGPointMake(CGRectGetMidX(self.frame),
CGRectGetMidY(self.frame));
CGMutablePathRef pathLeftContainer = CGPathCreateMutable();
// Draw circle with radius 20
CGPathAddArc(pathLeftContainer, NULL, 0, 20, 20, 0, 2*M_PI, true);
[leftContainer setPath:pathLeftContainer];
leftContainer.lineWidth = 10.0;
leftContainer.strokeColor = [UIColor redColor];
leftContainer.physicsBody = [SKPhysicsBody bodyWithEdgeChainFromPath:leftContainer.path];
leftContainer.physicsBody.dynamic = FALSE;
[leftContainer.physicsBody setAllowsRotation:FALSE];
[self addChild:leftContainer];
CGPathRelease(pathLeftContainer);

Related

Rotating a CAShapeLayer arc about its center using CABasicAnimation

I have an arc that I have drawn using CAShapeLayer and I want it to rotate around the circle's center. I am trying to get this animation using a CABasicAnimation on the 'transform.rotation' property. But the rotation seems is happening about a point that is not the same as the circle's center.
-(void)drawRect:(CGRect)rect{
int radius = 100;
CAShapeLayer *circle = [CAShapeLayer layer];
circle.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 2.0*radius, 2.0*radius) cornerRadius:radius].CGPath;
circle.fillColor = [UIColor orangeColor].CGColor;
circle.strokeColor = [UIColor blueColor].CGColor;
circle.lineWidth = 5;
circle.strokeStart = 0.0f;
circle.strokeEnd = 0.1f;
[self.layer addSublayer:circle];
CABasicAnimation *spinAnimation = [CABasicAnimation animationWithKeyPath:#"transform.rotation"];
spinAnimation.byValue = [NSNumber numberWithFloat:2.0f*M_PI];
spinAnimation.duration = 4;
spinAnimation.repeatCount = INFINITY;
[circle addAnimation:spinAnimation forKey:#"indeterminateAnimation"];
}
I know its an old problem, but whats the way out. I have tinkered a lot by setting the layer's bounds or the anchor point but it doesn't rotate about the center yet.
circle.bounds = self.frame;
Here is how I add the view to the view controller.
[self.view addSubview:[[ProgressIndicator alloc] initWithFrame:CGRectMake(50, 50, 200, 200)]];
This is what I eventually did.
The mistake was to add the animation to the sublayer and not the layer.
There is no need to tinker with anchorPoint or position here when the rotation is just needed about the center of the circle.
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor clearColor];
int radius = 50;
CAShapeLayer *circle = [CAShapeLayer layer];
circle.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 2.0*radius, 2.0*radius) cornerRadius:radius].CGPath;
circle.fillColor = [UIColor clearColor].CGColor;
circle.strokeColor = [UIColor blueColor].CGColor;
circle.lineWidth = 5;
circle.strokeStart = 0.0f;
circle.strokeEnd = 0.1f;
[self.layer addSublayer:circle];
}
return self; }
- (void)drawRect:(CGRect)rect {
CABasicAnimation *spinAnimation = [CABasicAnimation animationWithKeyPath:#"transform.rotation"];
spinAnimation.byValue = [NSNumber numberWithFloat:2.0f*M_PI];
spinAnimation.duration = 4;
spinAnimation.repeatCount = INFINITY;
[self.layer addAnimation:spinAnimation forKey:#"indeterminateAnimation"]; }
Think is better to do something like this)
CGFloat center = CGRectGetWidth(frame) / 2;
CGFloat lineWidth = 5;
CGFloat radius = center - lineWidth / 2;
CGRect bounds = frame;
bounds.origin = CGPointZero;
CAShapeLayer *spinLayer = [CAShapeLayer layer];
spinLayer.path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(center, center) radius:radius startAngle:0 endAngle:0.2 clockwise:YES].CGPath;
spinLayer.fillColor = [UIColor clearColor].CGColor;
spinLayer.strokeColor = [UIColor blueColor].CGColor;
spinLayer.lineWidth = 5;
spinLayer.lineCap = kCALineCapRound;
spinLayer.bounds = bounds;
spinLayer.position = CGPointMake(center, center);
[self.layer insertSublayer:spinLayer above:nil];
And animation:
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:#"transform.rotation"];
animation.byValue = [NSNumber numberWithFloat:2.f * M_PI];
animation.duration = 1.5f;
animation.repeatCount = INFINITY;
[spinLayer addAnimation:animation forKey:#"lineRotation"];
[self setNeedsLayout];
Swift 3
var bounds = frame
bounds.origin = CGPoint.zero
let center: CGFloat = frame.size.width
let lineWidth: CGFloat = 5
let radius = center - lineWidth / 2
let spinLayer = CAShapeLayer()
spinLayer.path = UIBezierPath(arcCenter: CGPoint(x: center, y: center),
radius: radius,
startAngle: 0,
endAngle: 0.2,
clockwise: true).cgPath
spinLayer.strokeColor = UIColor.blue.cgColor
spinLayer.fillColor = UIColor.clear.cgColor
spinLayer.lineWidth = lineWidth
spinLayer.lineCap = kCALineCapRound
spinLayer.bounds = bounds
spinLayer.position = CGPoint(x: center, y: center)
view.layer.insertSublayer(spinLayer, above: nil)
let rotation = CABasicAnimation(keyPath: "transform.rotation")
rotation.byValue = NSNumber(value: 2*M_PI as Double)
rotation.duration = 1
rotation.repeatCount = Float.infinity
spinLayer.add(rotation, forKey: "lineRotation")

Objective-c SpriteKit CGRectMake left border

I'm trying to draw vertical line on the left border of screen, but line is't showed. What is wrong?
CGRect leftRect = CGRectMake(0, 0, 10, self.size.height);
SKShapeNode *leftBorder = [SKShapeNode shapeNodeWithRect:leftRect];
leftBorder.strokeColor = [SKColor redColor];
leftBorder.fillColor = [SKColor redColor];
leftBorder.name = #"leftBorder";
leftBorder.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:leftBorder.frame];
leftBorder.physicsBody.dynamic = NO;
[self addChild:leftBorder];
You must set size gameScene ,when u init it.
_gameScene = [GameScene unarchiveFromFile:#"GameScene"];
// Here
_gameScene.size = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height);
_gameScene.scaleMode = SKSceneScaleModeAspectFill;
[skView presentScene:_gameScene];
Try this out
SKShapeNode *yourline = [SKShapeNode node];
CGMutablePathRef pathToDraw = CGPathCreateMutable();
CGPathMoveToPoint(pathToDraw, NULL, 100.0, 100.0);
CGPathAddLineToPoint(pathToDraw, NULL, 50.0, 50.0);
yourline.path = pathToDraw;
[yourline setStrokeColor:[UIColor redColor]];
[self addChild:yourline];
If it's not working, than it can be self. Be sure, that self is instance of SKScene.

Gradient as circle stroke color in CAShapeLayer

CAShapeLayer *circle = [CAShapeLayer layer];
circle.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(x, y, 100, 100) cornerRadius:50].CGPath;
// Configure the apperence of the circle
circle.fillColor = [UIColor whiteColor].CGColor;
circle.strokeColor = [UIColor darkGrayColor].CGColor;
circle.lineWidth = 1.8;
circle.lineDashPattern = #[#6, #3];
// Add to parent layer
[cell.layer addSublayer:circle];
I am using this code to draw a circle. Now, I want to use a gradient as stroke color. How can I do that?

how to position a rotating CAShapeLayer at certain point in UIImageView?

I have the following code which makes an oval rotating around its center. I would like to be able to position it within UIImageView at a certain position (say a middle of the view).
I would really appreciate if someone could help me out on this one.
-(void)drawCircle
{
CGMutablePathRef circlePath = CGPathCreateMutable();
int radius = 400;
CGRect circleRect = CGRectMake(CENTER_Y-radius*0.7, CENTER_X-radius, 1.4*radius, 2*radius);
float midX = CGRectGetMidX(circleRect);
float midY = CGRectGetMidY(circleRect);
CGAffineTransform transform = CGAffineTransformMakeTranslation(-midX, -midY);
CGPathAddEllipseInRect( circlePath ,&transform , circleRect);
CAShapeLayer *circle = [[CAShapeLayer alloc] init];
circle.path = circlePath;
circle.opacity = 0.1;
circle.contentsScale = SCREEN_SCALE;
circle.fillColor = [UIColor blueColor].CGColor;
[aView.layer addSublayer:circle];
CABasicAnimation* theAnimation = [CABasicAnimation animationWithKeyPath:#"transform.rotation.z"];
theAnimation.fromValue = 0;
theAnimation.toValue = #(2*M_PI);
theAnimation.duration=3.5;
theAnimation.autoreverses=FALSE;
theAnimation.repeatCount=HUGE_VALF;
theAnimation.fillMode = kCAFillModeBoth;
theAnimation.removedOnCompletion=FALSE;
theAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[circle addAnimation:theAnimation forKey:#"transform.rotation.z"];
}
a missing piece:
[circle setPosition:CGPointMake(CENTER_X, CENTER_Y)];

Rounder corners in UIView

i have a UIView and i would like to round it and add shadow color like this image :
For Rounder Corner
CAShapeLayer * maskLayer = [CAShapeLayer layer];
maskLayer.path = [UIBezierPath bezierPathWithRoundedRect: self.bounds byRoundingCorners: UIRectCornerBottomLeft | UIRectCornerTopRight cornerRadii: (CGSize){10.0, 10.}].CGPath;
self.layer.mask = maskLayer;
For Shadow
self.layer.masksToBounds = NO;
self.layer.shadowOffset = CGSizeMake(-15, 20);
self.layer.shadowRadius = 5;
self.layer.shadowOpacity = 0.5;
Hope this helps you!
To get the very same shadow as your image I would recommend you using a background image. Otherwise you should include <Quartzcore/Quartzcore.h> and use the following code:
view.layer.cornerRadius = 10;
view.frame = CGRectMake(15, 15, 100, 100);
view.backgroundColor = [UIColor redColor];
view.layer.shadowColor = [UIColor blackColor].CGColor;
view.layer.shadowOffset = CGSizeMake(2.0, 2.0);
view.layer.shadowOpacity = 0.8;
view.layer.shadowRadius = 10;
Some more information for the background image-option
Create a UIView that has the same width and height as the image including the shadow and assign the image to it this way:
view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"backgroundview.png"]];