簡體   English   中英

在 flutter 中使用自定義筆畫帽創建自定義圓形進度指示器

[英]Create custom circular progress indicator in flutter with custom stroke cap

我需要創建這個百分比指標在此處輸入圖像描述

我怎樣才能做到這一點? 我在 Flutter 中嘗試過 percent_indicator package,但主要問題是我們的 strokeCap 選項數量有限。 我也嘗試過用兩條弧線來做到這一點,但問題仍然存在。 有沒有一種方法可以創建自定義的 strokeCap,或者沒有 canvas.drawArc 的另一種方法?

您可以使用 CustomPainter 實現此目的。 下面是我的解決方案。

注意您可以傳入一個動態值來更新進度條的值。 我沒有這樣做,因為一旦渲染正確,實現它應該是微不足道的;)。 您還可以更新 colors 以滿足您的需要!

import 'package:flutter/material.dart';
import 'package:vector_math/vector_math.dart' as vmath;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: TestPage(),
    );
  }
}

class TestPage extends StatelessWidget {
  const TestPage({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          width: 200,
          height: 200,
          child: CustomPaint(
            painter: MyPainter(),
            child: Container(),
          ),
        ),
      ),
    );
  }
}

class MyPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final center = Offset(size.width / 2, size.height / 2);

    canvas.drawCircle(
      center,
      85,
      Paint()
        ..style = PaintingStyle.stroke
        ..color = Colors.black12
        ..strokeWidth = 30,
    );
    canvas.saveLayer(
      Rect.fromCenter(center: center, width: 200, height: 200),
      // Paint()..blendMode = BlendMode.dstIn,
      Paint(),
    );
    canvas.drawArc(
      Rect.fromCenter(center: center, width: 170, height: 170),
      vmath.radians(0),
      vmath.radians(200),
      false,
      Paint()
        ..style = PaintingStyle.stroke
        ..strokeCap = StrokeCap.round
        ..color = Colors.green[100]
        ..strokeWidth = 30,
    );

    canvas.drawArc(
      Rect.fromCenter(center: center, width: 155, height: 155),
      vmath.radians(0),
      vmath.radians(360),
      false,
      Paint()
        ..style = PaintingStyle.stroke
        ..strokeCap = StrokeCap.round
        ..color = Colors.green
        ..strokeWidth = 15
        ..blendMode = BlendMode.srcIn,
    );
    canvas.restore();
  }

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

您應該得到一個 output,如下所示: 在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM