[英]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.