paint method
Called whenever the object needs to paint. The given Canvas has its
coordinate space configured such that the origin is at the top left of the
box. The area of the box is the size of the size argument.
Paint operations should remain inside the given area. Graphical operations outside the bounds may be silently ignored, clipped, or not clipped. It may sometimes be difficult to guarantee that a certain operation is inside the bounds (e.g., drawing a rectangle whose size is determined by user inputs). In that case, consider calling Canvas.clipRect at the beginning of paint so everything that follows will be guaranteed to only draw within the clipped area.
Implementations should be wary of correctly pairing any calls to Canvas.save/Canvas.saveLayer and Canvas.restore, otherwise all subsequent painting on this canvas may be affected, with potentially hilarious but confusing results.
To paint text on a Canvas, use a TextPainter.
To paint an image on a Canvas:
-
Obtain an ImageStream, for example by calling ImageProvider.resolve on an AssetImage or NetworkImage object.
-
Whenever the ImageStream's underlying ImageInfo object changes (see ImageStream.addListener), create a new instance of your custom paint delegate, giving it the new ImageInfo object.
-
In your delegate's paint method, call the Canvas.drawImage, Canvas.drawImageRect, or Canvas.drawImageNine methods to paint the ImageInfo.image object, applying the ImageInfo.scale value to obtain the correct rendering size.
Implementation
@override
void paint(Canvas canvas, Size size) {
Paint cPaint = Paint()..style = PaintingStyle.fill; // 圆的绘制画笔
Paint bPaint = Paint()..style = PaintingStyle.fill; // 波浪的绘制画笔
double cX = width / 2; // 圆心横坐标
double cY = height / 2; // 圆心纵坐标
// 设置圆的颜色
if (circleColors == null) {
cPaint.color = Colors.blue;
} else if (circleColors!.isEmpty) {
cPaint.color = Colors.blue;
} else if (circleColors!.length == 1) {
cPaint.color = circleColors![0];
} else {
cPaint.shader = ui.Gradient.linear(
const Offset(0.0, 0.0),
Offset(width, height),
circleColors!,
);
}
// 如果需要在圆上方显示波浪,则先绘制圆
if (centerCircle && overCircle) {
canvas.save();
canvas.drawCircle(Offset(cX, cY), waves[0].minRadius, cPaint);
canvas.restore();
}
// 遍历波浪列表,设置各种属性并绘制波浪
for (WaveDrawable wave in waves) {
// 设置波浪的最大和最小半径
if (wave.maxRadius < 0) {
double max = width / 2 / 1.25;
wave.setMaxRadius(max);
}
if (wave.minRadius < 0) {
double min = width / 2 / 1.5;
wave.setMinRadius(min);
}
wave.setAmplitude(amplitude); // 设置波浪振幅
wave.setScale(scale); // 设置波浪缩放比例
wave.setMaxSpeed(speed); // 设置波浪最大速度
wave.setAutoScale(autoScale); // 设置是否自动缩放
// 设置波浪颜色
if (colors != null) {
wave.setColors(colors!);
}
canvas.save();
wave.draw(canvas, bPaint, Size(cX, cY)); // 绘制波浪
canvas.restore();
}
// 如果需要在圆中心显示波浪,则绘制圆
if (centerCircle && !overCircle) {
canvas.save();
canvas.drawCircle(Offset(cX, cY), waves[0].minRadius, cPaint);
canvas.restore();
}
}