老孟導讀:CustomPaint能夠稱之爲動畫鼻祖,它能夠實現任何酷炫的動畫和效果。CustomPaint自己沒有動畫屬性,僅僅是繪製屬性,通常狀況下,CustomPaint會和動畫控制配合使用,達到理想的效果。javascript
基本用法
CustomPaint的基本用法中包含繪製點、線、各類形狀和各類曲線,用法以下:css
CustomPaint( painter: MyCustomPainter(),)
MyCustomPainter定義以下:java
class MyCustomPainter extends CustomPainter { void paint(Canvas canvas, Size size) {}
bool shouldRepaint(MyCustomPainter oldDelegate) { return this != oldDelegate; }}
上面的MyCustomPainter爲了看起來清晰,什麼也沒有作,一般狀況下,在paint
方法內繪製自定義的效果。shouldRepaint
方法一般在當前實例和舊實例屬性不一致時返回true。canvas
paint
經過canvas
繪製,size
爲當前控件的大小,下面看看canvas
的方法。微信
繪製點
Paint _paint = Paint() ..color = Colors.red ..strokeWidth = 3;
@override void paint(Canvas canvas, Size size) { var points = [ Offset(0, 0), Offset(size.width / 2, size.height / 2), Offset(size.width, size.height), ]; canvas.drawPoints(PointMode.points, points, _paint); }
PointMode
有3種模式:app
points:點編輯器
lines:將2個點繪製爲線段,若是點的個數爲奇數,最後一個點將會被忽略ide
polygon:將整個點繪製爲一條線函數
繪製線
canvas.drawLine(Offset(0, 0),Offset(size.width, size.height), _paint);
繪製路徑
Paint _paint = Paint() ..color = Colors.red ..style = PaintingStyle.stroke ..strokeWidth = 3;
@overridevoid paint(Canvas canvas, Size size) { print('size:$size'); var _path = Path() ..moveTo(0, 0) ..lineTo(size.width, 0) ..lineTo(size.width, size.height) ..close(); canvas.drawPath(_path, _paint);}
這裏注意Paint.style
,還能夠設置爲PaintingStyle.fill
,效果以下:動畫
此時Path的路徑不要在一條直線上,不然會看不到效果。
繪製各類形狀
繪製圓形
canvas.drawCircle(Offset(size.width/2, size.height/2), 20, _paint);
繪製橢圓
canvas.drawOval(Rect.fromLTRB(0, 0, size.width, size.height/2), _paint);
若是給定的Rect爲正方形,那麼橢圓將會變爲圓形。
繪製弧
canvas.drawArc( Rect.fromLTRB(0, 0, size.width, size.height), 0, pi/2, true, _paint);
繪製圓角矩形
canvas.drawRRect( RRect.fromLTRBR(0, 0, size.width, size.height, Radius.circular(10)), _paint)
canvas
還有不少繪製函數,好比貝塞爾曲線、三次貝塞爾曲線、畫布的反轉等操做,這裏不在一一介紹。
這些函數和Android的Canvas基本同樣,若是你有Android基礎,直接套用便可。
最後奉上一個繪製玫瑰的動畫效果:
這個效果是否是很酷炫,咱們看下繪製花骨朵代碼:
////// 繪製花骨朵///_drawFlower(Canvas canvas, Size size) { //將花變爲紅色 if (flowerPaths.length >= RoseData.flowerPoints.length) { var path = Path(); for (int i = 0; i < flowerPaths.length; i++) { if (i == 0) { path.moveTo(flowerPaths[i].dx, flowerPaths[i].dy); } else { path.lineTo(flowerPaths[i].dx, flowerPaths[i].dy); } } _paint.style = PaintingStyle.fill; _paint.color = _flowerColor; canvas.drawPath(path, _paint); } //繪製線 _paint.style = PaintingStyle.stroke; _paint.color = _strokeColor; //去掉最後2個點,最後2個點爲了繪製紅色 var points = flowerPaths.sublist(0, max(0, flowerPaths.length - 2)); canvas.drawPoints(PointMode.polygon, points, _paint);}
花骨朵的繪製只經過canvas.drawPath
就實現了,其實整個玫瑰花的繪製都是經過canvas.drawPath
加上動畫控制實現的。
CustomPaint能夠實現任何你想要的動畫的效果,好比繪畫版就能夠經過此控件實現。
獲取完整繪製玫瑰代碼關注公衆號回覆:rose



本文分享自微信公衆號 - 老孟Flutter(lao_meng_qd)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。