如何在 flutter 中使用 CustomPainter 绘制圆环?

How to draw a ring with CustomPainter in flutter?

我正在尝试使用 CustomPainter class 绘制一个半环,您可以在下图中看到(浅紫色和浅橙色)但无法绘制。 我只会画圆、方和线

代码:

class MakeCircle extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint();
    paint.color = Colors.white12;
    var position = Offset(size.width /10, size.height / 10);
    canvas.drawCircle(position, 40.0, paint);
  }
  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}

这个只能画圆

您必须为您的 Paint 对象使用 PaintingStyle.stroke 并且还要使用 Path class 绘制你的 arc

我给你创建了一个例子,请测试一下:

import 'dart:math' as math;

import 'package:flutter/material.dart';

main() {
  runApp(MaterialApp(
    home: Home(),
  ));
}

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: SizedBox(
          width: 300,
          height: 300,
          child: CustomPaint(
            painter: MakeCircle(strokeWidth: 50,strokeCap: StrokeCap.round),
          ),
        ),
      ),
    );
  }
}




class MakeCircle extends CustomPainter {
  final double strokeWidth;
  final StrokeCap strokeCap;

  MakeCircle({this.strokeCap = StrokeCap.square, this.strokeWidth = 10.0});

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.blue
      ..strokeCap = StrokeCap.round
      ..strokeWidth = strokeWidth
      ..style = PaintingStyle.stroke; //important set stroke style

    final path = Path()
      ..moveTo(strokeWidth, strokeWidth)
      ..arcToPoint(Offset(size.width - strokeWidth, size.height - strokeWidth),
          radius: Radius.circular(math.max(size.width, size.height)));

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}