Home > Software engineering >  Flutter_I have a question about rotate canvas
Flutter_I have a question about rotate canvas

Time:07-23

I am drawing shapes using canvas and customPaint as shown in the image below. And I'm going to drag each shape to rotate it.

I knew that I could rotate it through the canvas.rotate. But if I use this, there's a problem with all the shapes rotating the same.

The following is part of my code.

class Shape {}
class Rectangle extends Shape {
  Rect? rect;
  double? left, top;
  bool? isRectSelected;

  final paint = Paint();

  Rectangle(Color color, double width) {
    this.paint
      ..color = color
      ..isAntiAlias = true
      ..strokeCap = StrokeCap.round
      ..strokeWidth = width
      ..style = PaintingStyle.stroke; // no fill
  }

// ========================

class Sketcher extends CustomPainter {
  final List<Shape> shapes;

  Sketcher(
    this.shapes,
  ) : super();

  @override
  void paint(Canvas canvas, Size size) {
    for (var shape in shapes) {
      if (shape is Rectangle) {    
        final degrees = 30; // angle
        final radians = degrees * math.pi / 180;

        // ! If use it, all shape rotate same angle
        canvas.translate(shape.rect!.left, shape.rect!.top); // left top 
        canvas.rotate(radians); 
        canvas.translate(-shape.rect!.left, -shape.rect!.top);

        // ractangle shape
        canvas.drawRect(shape.rect!, shape.paint);
      }

    // same code circle...
    }
  }

enter image description here

How do I rotate each shape instead of the entire canvas? Could you tell me how to do this?

CodePudding user response:

You can use canvas.save() to save the state the canvas then adjust the canvas according to your need and then use canvas.restore() to restore the canvas to the state before save(). The action inside the save-restore action will still be draw to the canvas.

canvas.save();
// do something
// canvas.rotate(radians);
// canvas.drawRect();  // this rect will be rotated
canvas.restore();

canvas.drawRect();  // this rect will not be rotated
  • Related