SpriteKitで図形を描画する
SpriteKitはSKShapeNodeという図形を描画するクラスを保持しています。
SKShapeNodeを使えば簡単に図形を書くことができます。Swift4で書いていきます。
SKShapeNodeで図形の描画
円
let ellipse = SKShapeNode(circleOfRadius: 200)
ellipse.position = CGPoint(x:self.frame.midX, y:self.frame.midY)
ellipse.fillColor = .red
実行時の画像
四角
let rect = SKShapeNode(rectOf: CGSize(width: 100, height: 100))
rect.position = CGPoint(x:self.frame.midX, y:self.frame.midY)
rect.fillColor = .blue
self.addChild(rect)
実行時の画像
三角
let length: CGFloat = 200
var points = [CGPoint(x:length, y:-length / 2.0),
CGPoint(x:-length, y:-length / 2.0),
CGPoint(x: 0.0, y: length),
CGPoint(x:length, y:-length / 2.0)]
let triangle = SKShapeNode(points: &points, count: points.count)
triangle.fillColor = .yellow
triangle.position = CGPoint(x:self.frame.midX, y:self.frame.midY)
self.addChild(triangle)
実行時の画像
おでん
//skewer
let skewer = SKShapeNode(rectOf: CGSize(width: 10, height: 1500))
skewer.position = CGPoint(x:self.frame.midX, y:self.frame.midY)
skewer.fillColor = .green
self.addChild(skewer)
//ellipse
let ellipse = SKShapeNode(circleOfRadius: 200)
ellipse.position = CGPoint(x:self.frame.midX, y:self.frame.midY)
ellipse.fillColor = .red
self.addChild(ellipse)
//rect
let rect = SKShapeNode(rectOf: CGSize(width: 300, height: 300))
rect.position = CGPoint(x:self.frame.midX, y:self.frame.midY - 350)
rect.fillColor = .blue
self.addChild(rect)
//triangle
let length: CGFloat = 200
var points = [CGPoint(x:length, y:-length / 2.0),
CGPoint(x:-length, y:-length / 2.0),
CGPoint(x: 0.0, y: length),
CGPoint(x:length, y:-length / 2.0)]
let triangle = SKShapeNode(points: &points, count: points.count)
triangle.fillColor = .yellow
triangle.position = CGPoint(x:self.frame.midX, y:self.frame.midY + 300)
self.addChild(triangle)