Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw a circular SKSpriteNode with texture?

Is there a way to draw a circular SKSpriteNode with texture? Or alternatively, draw a SKShapeNode with texture?

like image 318
Lim Thye Chean Avatar asked Nov 22 '25 22:11

Lim Thye Chean


1 Answers

It is to consider that all images are rectangle/squares. What we see as round, is how we show colored pixels: what is outside the circle, is transparent and what is inside, is the colored part.

  1. we need a circle
  2. we texture it
  3. we add it to the scene
  4. we take back a new texture from this shape node that we just added to the scene
  5. we make a new sprite using this new texture
  6. we add the sprite to the scene

    let shape: SKShapeNode = SKShapeNode(circleOfRadius: 50)
    shape.name = "shape"
    shape.lineWidth = 1 // this way we see that this is a circle
    shape.fillColor = .white // to see the true colors of our image
    //shape.strokeColor = .white
    //shape.glowWidth = 0
    shape.fillTexture = SKTexture(imageNamed:"myImage")
    shape.position = CGPoint(x: 0, y:200)
    self.addChild(shape)
    
    let newTexture: SKTexture = (self.view?.texture(from: self.childNode(withName: "shape")!))!
    let sprite: SKSpriteNode = SKSpriteNode(texture: newTexture)
    self.addChild(sprite) 
    
    shape.removeFromParent()
    
like image 75
hungry Avatar answered Nov 25 '25 17:11

hungry