Search code examples
canvasswiftuitextrotation

How to rotate text in canvas in SwiftUI?


I didn't find the way to rotate text at 90° in the canvas using the context in SwiftUI (iOS 16).

Here is my code:

Canvas { context, size in

  context.rotate(by: Angle(degrees: 90)) // doesn't work because it surely rotates all the canvas
            
  let text = Text(String(drinkFrom)).font(.custom("HelveticaNeue", size: 12)).foregroundColor(.textUnselected)
     
  //.rotationEffect(Angle(degrees: 90), anchor: UnitPoint(x: drinkFromOriginX, y: size.height/2)) // doesn't work because it's can't be resolved by the context
            
     context.draw(text, at: CGPoint(x: drinkFromOriginX, y: size.height/2), anchor: .center)
    }
 }

I would like to rotate the text around it's center, using its position. What did I miss ?

Thanks.


Solution

  • You can create a new layer and modify that one independently from the main context:

    struct ContentView: View {
        var body: some View {
            Canvas { context, size in
                            
                let text = Text("Example Text")
                    .font(.headline).foregroundColor(.blue)
                
                context.drawLayer { ctx in // adds a layer that can be indepentently modified
                    ctx.translateBy(x: size.width/2, y: size.height/2) // move to center
                    ctx.rotate(by: Angle(degrees: 90)) // rotate
                    ctx.draw(text, at: CGPoint(x: 0, y: 0), anchor: .center) // draw text
                }
            }
        }
    }