小菜想自定義一個水波紋按鈕,即預設向外擴散的水波樣式;實作方式有很多種,小菜嘗試最基本的 AnimationController 逐層繪制來處理,小菜簡單記錄一下嘗試過程;
ACEWaterButton
小菜畫了一個簡單的圖如下,預期的水波紋按鈕包括兩層,以中心圓(藍色)為基礎逐漸向外圍擴散至(綠色),并循環重複;

1. 内置圓
小菜以此分為兩步,第一步先繪制内置圓和内置圖示,小菜提供了 innerSize 和 innerIcon 屬性以友善内置圓的樣式自定義;通過 ClipOval 裁切一個完整的内置圓;
其中需要注意的是,内置圓應置于外圍圓的中心,是以小菜添加一個 outSize 屬性限制外圍圓尺寸,同時預設設定 innerSize = 48.0,若未設定 outSize,則以 innerSize * 2 為預設值;
Container(
width: widget.outSize ?? widget.innerSize * 2,
height: widget.outSize ?? widget.innerSize * 2,
child: widget.innerIcon == null
? Container() : Center(child: ClipOval(
child: Container(
width: widget.innerSize,
height: widget.innerSize,
color: widget.color,
child: widget.innerIcon))))
2. 水波紋
小菜預想實作水波紋效果則必然離不開 Animation 動畫,使用動畫方式也有多種,可以繼承 AnimatedWidget 也可以使用 AnimationController 自定義動畫樣式;
小菜預期水波紋不僅範圍逐漸變大,并且在擴散過程中透明度逐漸降低,至外圍最大範圍為止消失;小菜采用最基本的 CustomPainter 自定義 Canvas.drawCircle,根據時間進度來逐層繪制水波紋;
2.1 透明度
小菜使用 Paint 繪制時根據 AnimationController.value 進度逐漸設定 color.withOpacity 透明度逐漸變低;
Paint _paint = Paint()..style = PaintingStyle.fill;
_paint..color = color.withOpacity(1.0 - progress);
2.2 外圍圓
外圍圓主要是根據 AnimationController.value 進度逐漸進行半徑的更新;小菜預期的水波紋範圍隻有預設的内置圓到外圍圓的範圍漸變,是以變動範圍為 (outSize - innerSize) 0.5 progress,同時起始位置為内置圓,是以初始半徑應再加上内置圓半徑;
double _radius = ((outSize ?? innerSize * 2) * 0.5 - innerSize * 0.5) * progress + innerSize * 0.5;
canvas.drawCircle(Offset(size.width * 0.5, size.height * 0.5), _radius, _paint);
小菜在測試過程中也嘗試了其他的擴充範圍,若起始位置為中心則無需添加内置圓半徑;若想增大或見效水波紋範圍可以自由調整 AnimationController.value 進度範圍;
// 中心點擴充
double _radius = innerSize * 0.5 * progress;
// 增大擴充範圍
double _radius = innerSize * 2 * progress;
class ACEWaterPainter extends CustomPainter {
final double progress;
final Color color;
final double innerSize;
final double outSize;
Paint _paint = Paint()..style = PaintingStyle.fill;
ACEWaterPainter(this.progress, this.color, this.innerSize, this.outSize);
@override
void paint(Canvas canvas, Size size) {
_paint..color = color.withOpacity(1.0 - progress);
double _radius =
((outSize ?? innerSize * 2) * 0.5 - innerSize * 0.5) * progress + innerSize * 0.5;
canvas.drawCircle(Offset(size.width * 0.5, size.height * 0.5), _radius, _paint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) => true;
}
3. 小反思
3.1 内置圓是否可預設?
小菜在通過 ACEWaterPainter 繪制水波紋過程中,起始位置從内置圓開始,那是否可以省略第一步的内置圓呢?
暫時先不預設,因為小菜在設定水波紋擴散過程中,同時設定了透明度的漸變,若預設内置圓會影響 innerIcon 的展示效果;但内置圓繪制位置可以調整,也可以在 ACEWaterPainter 中進行繪制;
3.2 shouldRepaint 是否需要一直重繪?
ACEWaterPainter 中是否需要一直重繪;在使用自定義 Paint 委托類建立新的 CustomPaint 對象時若新執行個體與舊執行個體不同,則應傳回 true,否則應傳回 false;是以在水波紋過程中,小菜預設設定為 true 進行重繪;
ACEWaterButton 案例源碼小菜對 ACEWaterButton 水波紋按鈕的簡單效果已滿足,但還不夠完善,對于重繪的機制還需要優化;如有錯誤,請多多指導!
來源: 阿策小和尚