Flutter 五维雷达图(新增动画效果)
2020-12-17 本文已影响0人
旺仔_100
flutter 五维雷达图.png
思路:
一、绘制5个正五边形,按照五边形的半径等分绘制。至于五边形需要计算出5个定点的位置。绘制一个正五边形,一个顶点在y轴上,半径为r,s标识sin,c标识cos顺势正依次是(0,r)(rc18,rs18)(rc54,-rs54)(-rc54,-rs54)(-rc18,rs18),然后注意角度需要转换成程序需要的弧度angle / 180.0 * pi,然后使用path连接即可。
思路:
一、绘制5个正五边形,按照五边形的半径等分绘制。至于五边形需要计算出5个定点的位置。绘制一个正五边形,一个顶点在y轴上,半径为r,s标识sin,c标识cos顺势正依次是(0,r)(rc18,rs18)(rc54,-rs54)(-rc54,-rs54)(-rc18,rs18),然后注意角度需要转换成程序需要的弧度angle / 180.0 * pi,然后使用path连接即可。
///画n个五边形
for (int i = 0; i < n; i++) {
List<Offset> points = [
Offset(0, -r * (i + 1) / n),
Offset(r * (i + 1) / n * cos(angleToRadian(18)),
-r * (i + 1) / n * sin(angleToRadian(18))),
Offset(r * (i + 1) / n * cos(angleToRadian(54)),
r * (i + 1) / n * sin(angleToRadian(54))),
Offset(-r * (i + 1) / n * cos(angleToRadian(54)),
r * (i + 1) / n * sin(angleToRadian(54))),
Offset(-r * (i + 1) / n * cos(angleToRadian(18)),
r * (i + 1) / n * -sin(angleToRadian(18))),
];
drawPentagon(points, canvas, pentagonPaint);
}
///画五边形
void drawPentagon(List<Offset> points, Canvas canvas, Paint paint) {
Path path = Path();
path.moveTo(0, points[0].dy);
for (int i = 1; i < points.length; i++) {
path.lineTo(points[i].dx, points[i].dy);
}
path.close();
canvas.drawPath(path, paint);
}
二、连接原点和五个定点
void drawZeroToPoint(List<Offset> points, Canvas canvas) {
points.forEach((element) {
canvas.drawLine(
Offset.zero,
element,
zeroToPointPaint,
);
});
}
三、在绘制我们需要显示的雷达图,也是五边形,所以,只需要算出五个顶点就可以套用上面的绘制五边图绘制。
List<Offset> list = converPoint(points, score);
drawPentagon(list, canvas, contentPaint);
List<Offset> converPoint(List<Offset> points, List<RadarBean> score) {
List<Offset> list = [];
for (int i = 0; i < points.length; i++) {
list.add(points[i].scale(score[i].score / 100, score[i].score / 100));
}
return list;
}
四、因为5个顶点位置的文字都需要不同的调整,所以分别设置位置
///根据位置绘制文字
for (int i = 0; i < points.length; i++) {
int type = 0;
switch (i) {
case 0:
type = 1;
points[i] -= Offset(0, padding * 2);
break;
case 1:
type = 0;
points[i] += Offset(padding, -padding);
break;
case 2:
type = 1;
points[i] += Offset(bottomPadding, padding);
break;
case 3:
type = 1;
points[i] += Offset(-bottomPadding, padding);
break;
case 4:
type = 2;
points[i] -= Offset(padding, padding);
break;
default:
}
drawText(canvas, points[i], score[i].name,
TextStyle(fontSize: 14, color: Colors.black54), type);
}
/// 右边的文字不需要移动 有的文字要移动一半居中 左边的文字需要左移动整个距离
///type 0 1 2
void drawText(Canvas canvas, Offset offset, String text, TextStyle style,
int type) {
var textPainter = TextPainter(
text: TextSpan(text: text, style: style),
textAlign: TextAlign.center,
textDirection: TextDirection.rtl);
textPainter.layout();
Size size = textPainter.size;
Offset offsetResult;
switch (type) {
case 1:
offsetResult = Offset(offset.dx - size.width / 2, offset.dy);
break;
case 2:
offsetResult = Offset(offset.dx - size.width, offset.dy);
break;
default:
offsetResult = offset;
}
textPainter.paint(canvas, offsetResult);
}
实际上思路很简单,就是需要算顶点位置,然后文字位置处理并不优雅。
五、新增动画效果
思路:通过修改 ValueNotifier<List<Offset>> values 的值,可以触发重绘。使用AnimationController来控制values的值的变化,使用CurvedAnimation来增加一个加速插值器。
//创建一个1s的动画
ctrl = AnimationController(vsync: this, duration: Duration(seconds: 1))
..addListener(() {
//监听动画的进度,并修改对应的值,重绘
values.value = converPoint(widget.points, widget.scoreList, animation.value);
});
//关联控制器,设置加速器
animation = CurvedAnimation(parent: ctrl,curve: Curves.bounceOut);
添加动画需要注意的几个点:
- 动画需要用到SingleTickerProviderStateMixin 这个类
class RadarMapState extends State<RadarMap> with SingleTickerProviderStateMixin {
- ValueNotifier<List<Offset>>的值的修改,不能放到自定义的CustomPainter中,会无限重绘报错。还是在RadarMapState 中修改对应的值实现动画。
ctrl = AnimationController(vsync: this, duration: Duration(seconds: 1))
..addListener(() {
values.value = converPoint(widget.points, widget.scoreList, animation.value);
});
- 从什么时候开始动画呢?太早还未绘制完成,会报错。可以监听绘制完成,然后再去开始动画。
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
print("界面绘制完成");
ctrl.forward(from: 0);
});
附上整体代码
import 'dart:math';
import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
///五维雷达图
/// 设置雷达图的半径,根据分5等分来计算
/// 绘制一个正五边形,一个顶点在y轴上,半径为r,顺势正依次是(0,r)(r*c18,r*s18)
/// (r*c54,-r*s54)(-r*c54,-r*s54)(-r*c18,r*s18)
///
class RadarBean {
double score;
String name;
RadarBean(this.score, this.name);
}
/// 右边的文字不需要移动 有的文字要移动一半居中 左边的文字需要左移动整个距离
///type 0 1 2
///
enum MoveType { noMove, halfMove, allMove }
class RadarMap extends StatefulWidget {
///半径
double r;
// static final double defaultR = setWidth(80.0);
///正五边形个数 目前只支持五边形
int n = 5;
///文字和图像的间距
double padding;
static const double defaultPadding = 10;
///最下面两个的间距
double bottomPadding = 8;
static const double defaultBottomPadding = 8;
static const double strokeWidth_0_5 = 0.5;
static const double strokeWidth_1 = 1;
static const double strokeWidth_2 = 2;
Paint zeroToPointPaint;
Paint pentagonPaint;
Paint contentPaint;
///当前的分数 ///对应的文案
List<RadarBean> scoreList;
List<Offset> points;
RadarMap(this.scoreList,
{this.r,
this.padding = defaultPadding,
this.bottomPadding = defaultBottomPadding,
this.zeroToPointPaint,
this.pentagonPaint,
this.contentPaint}) {
assert(scoreList.length == 5);
r = 80.0;
///原点到5个定点的连线
zeroToPointPaint = Paint()
..style = PaintingStyle.stroke
..color = Colors.black12
..strokeWidth = strokeWidth_0_5;
///5层五边形画笔
pentagonPaint = Paint()
..color = Colors.black12
..strokeWidth = strokeWidth_1
..style = PaintingStyle.fill;
///覆盖内容颜色
contentPaint = Paint()
..color = Colors.lightBlue[300].withAlpha(100)
..strokeWidth = strokeWidth_2
..style = PaintingStyle.fill;
points = [
Offset(0, -r),
Offset(r * cos(angleToRadian(18)), -r * sin(angleToRadian(18))),
Offset(r * cos(angleToRadian(54)), r * sin(angleToRadian(54))),
Offset(-r * cos(angleToRadian(54)), r * sin(angleToRadian(54))),
Offset(-r * cos(angleToRadian(18)), r * -sin(angleToRadian(18))),
];
}
@override
State<StatefulWidget> createState() {
return RadarMapState();
}
}
class RadarMapState extends State<RadarMap>
with SingleTickerProviderStateMixin {
ValueNotifier<List<Offset>> values = ValueNotifier([]);
AnimationController ctrl;
Animation animation;
@override
void initState() {
// TODO: implement initState
super.initState();
ctrl = AnimationController(vsync: this, duration: Duration(seconds: 1))
..addListener(() {
values.value = converPoint(widget.points, widget.scoreList, animation.value);
});
animation = CurvedAnimation(parent: ctrl,curve: Curves.bounceOut);
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
print("界面绘制完成");
ctrl.forward(from: 0);
});
}
List<Offset> converPoint(
List<Offset> points, List<RadarBean> score, double scale) {
List<Offset> list = [];
for (int i = 0; i < points.length; i++) {
list.add(points[i]
.scale(score[i].score * scale / 100, score[i].score * scale / 100));
}
return list;
}
@override
Widget build(BuildContext context) {
return Container(
color: Colors.white,
child: CustomPaint(
painter: RadarmapPainter(widget.scoreList, ctrl, values,
r: widget.r,
n: widget.n,
padding: widget.padding,
bottomPadding: widget.bottomPadding,
zeroToPointPaint: widget.zeroToPointPaint,
pentagonPaint: widget.pentagonPaint,
contentPaint: widget.contentPaint),
),
);
}
}
class RadarmapPainter extends CustomPainter {
double r;
int n;
double padding;
double bottomPadding;
Paint zeroToPointPaint;
Paint pentagonPaint;
Paint contentPaint;
List<RadarBean> score;
AnimationController ctrl;
ValueNotifier<List<Offset>> values;
RadarmapPainter(this.score, this.ctrl, this.values,
{this.r,
this.n,
this.padding,
this.bottomPadding,
this.zeroToPointPaint,
this.pentagonPaint,
this.contentPaint})
: super(repaint: values);
@override
void paint(Canvas canvas, Size size) {
final List<Offset> points = [
Offset(0, -r),
Offset(r * cos(angleToRadian(18)), -r * sin(angleToRadian(18))),
Offset(r * cos(angleToRadian(54)), r * sin(angleToRadian(54))),
Offset(-r * cos(angleToRadian(54)), r * sin(angleToRadian(54))),
Offset(-r * cos(angleToRadian(18)), r * -sin(angleToRadian(18))),
];
canvas.save();
canvas.translate(size.width / 2, size.height / 2);
canvas.drawPoints(
PointMode.points,
[Offset(0, 0)],
Paint()
..color = Colors.green
..strokeWidth = 2);
///画n个五边形
for (int i = 0; i < n; i++) {
List<Offset> points = [
Offset(0, -r * (i + 1) / n),
Offset(r * (i + 1) / n * cos(angleToRadian(18)),
-r * (i + 1) / n * sin(angleToRadian(18))),
Offset(r * (i + 1) / n * cos(angleToRadian(54)),
r * (i + 1) / n * sin(angleToRadian(54))),
Offset(-r * (i + 1) / n * cos(angleToRadian(54)),
r * (i + 1) / n * sin(angleToRadian(54))),
Offset(-r * (i + 1) / n * cos(angleToRadian(18)),
r * (i + 1) / n * -sin(angleToRadian(18))),
];
drawPentagon(points, canvas, pentagonPaint);
}
///连接最外层的五个定点
drawZeroToPoint(points, canvas);
///修改成对应的分数,绘制覆盖内容
drawPentagon(values.value, canvas, contentPaint);
///根据位置绘制文字
drawTextByPosition(points, canvas);
canvas.restore();
}
///根据位置来绘制文字
void drawTextByPosition(List<Offset> points, Canvas canvas) {
for (int i = 0; i < points.length; i++) {
MoveType type = MoveType.noMove;
switch (i) {
case 0:
type = MoveType.halfMove;
points[i] -= Offset(0, padding * 2);
break;
case 1:
type = MoveType.noMove;
points[i] += Offset(padding, -padding);
break;
case 2:
type = MoveType.halfMove;
points[i] += Offset(bottomPadding, padding);
break;
case 3:
type = MoveType.halfMove;
points[i] += Offset(-bottomPadding, padding);
break;
case 4:
type = MoveType.allMove;
points[i] -= Offset(padding, padding);
break;
default:
}
drawText(canvas, points[i], score[i].name,
TextStyle(fontSize: 14, color: Colors.black54), type);
}
}
/// 右边的文字不需要移动 有的文字要移动一半居中 左边的文字需要左移动整个距离
void drawText(Canvas canvas, Offset offset, String text, TextStyle style,
MoveType type) {
var textPainter = TextPainter(
text: TextSpan(text: text, style: style),
textAlign: TextAlign.center,
textDirection: TextDirection.rtl);
textPainter.layout();
Size size = textPainter.size;
Offset offsetResult;
switch (type) {
case MoveType.halfMove:
offsetResult = Offset(offset.dx - size.width / 2, offset.dy);
break;
case MoveType.allMove:
offsetResult = Offset(offset.dx - size.width, offset.dy);
break;
default:
offsetResult = offset;
}
textPainter.paint(canvas, offsetResult);
}
void drawZeroToPoint(List<Offset> points, Canvas canvas) {
points.forEach((element) {
canvas.drawLine(
Offset.zero,
element,
zeroToPointPaint,
);
});
}
///画五边形
void drawPentagon(List<Offset> points, Canvas canvas, Paint paint) {
if(points.length == 0){
return;
}
Path path = Path();
path.moveTo(0, points[0].dy);
for (int i = 1; i < points.length; i++) {
path.lineTo(points[i].dx, points[i].dy);
}
path.close();
canvas.drawPath(path, paint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return false;
}
///转换角度 18/180.0 *pi
}
double angleToRadian(double angle) {
return angle / 180.0 * pi;
}