我正在开发一个 Flutter 项目,其中使用 SweepGradient 绘制一个半圆仪表,其渐变从红色过渡到黄色再到绿色。弧线整体看起来很棒,但我遇到了一个问题,渐变没有完全覆盖弧线的末端。
如上图所示,绿色没有完全到达弧线的末端。笔划帽设置为 StrokeCap.round,这对于我的设计来说是必要的,但它似乎导致渐变无法完全达到弧线末端的绿色。
这是要复制的代码:
import 'dart:math';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Custom Gauge Example')),
body: const Center(
child: CustomPaint(
size: Size(200, 100),
painter: GaugePainter(),
),
),
),
);
}
}
class GaugePainter extends CustomPainter {
const GaugePainter();
@override
void paint(Canvas canvas, Size size) {
const strokeWidth = 16.0;
final rect = Rect.fromLTWH(
strokeWidth / 2,
strokeWidth / 2,
size.width - strokeWidth,
size.height * 2 - strokeWidth * 2,
);
const gradient = SweepGradient(
startAngle: pi,
endAngle: pi * 2,
colors: [Colors.red, Colors.yellow, Colors.green],
);
final gradientShader = gradient.createShader(rect);
canvas.drawArc(
rect,
-pi,
pi,
false,
Paint()
..shader = gradientShader
..style = PaintingStyle.stroke
..strokeCap = StrokeCap.round
..strokeWidth = strokeWidth,
);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return false;
}
}
如何确保渐变完全覆盖圆弧的末端,以便正确显示绿色,同时仍保持圆形笔划帽?任何指导或建议将不胜感激!
试试这个:
const gradient = SweepGradient(
startAngle: 0,
endAngle: pi * 2,
colors: [Colors.green,Colors.red,Colors.red, Colors.yellow, Colors.green],
);