[英]Flutter_I have a question about rotate canvas
我正在使用canvas
和customPaint
绘制形状,如下图所示。 我将拖动每个形状来旋转它。
我知道我可以通过canvas.rotate
旋转它。 但是如果我使用它,所有形状都旋转相同会出现问题。
以下是我的代码的一部分。
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...
}
}
如何旋转每个形状而不是整个画布? 你能告诉我怎么做吗?
您可以使用canvas.save()保存画布的状态,然后根据需要调整画布,然后使用canvas.restore()将画布恢复到 save() 之前的状态。 save-restore 操作中的操作仍将绘制到画布上。
canvas.save();
// do something
// canvas.rotate(radians);
// canvas.drawRect(); // this rect will be rotated
canvas.restore();
canvas.drawRect(); // this rect will not be rotated
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.