再暸解了 CustomPainter 如何使用後我們可以來嘗試做出網格
先定義網格大小與寬高個數,在個別畫出直、橫線段
class SpacePainter extends CustomPainter {
Paint _paint ;
double gridSize = 0 ;
int widthCount = 8 ;
int heightCount = 14 ;
SpacePainter(){
_paint = Paint() ;
}
@override
void paint(Canvas canvas, Size size) {
//定義畫筆
_paint.color = Colors.blueGrey;
_paint.style = PaintingStyle.stroke ;
Path path = Path();
//根據高度跟高度格數算出 gridSize
gridSize = size.height/heightCount ;
//找出網格寬度與高度
double width = gridSize*widthCount;
double height = gridSize*heightCount ;
//找出網格起始位置
double startX = (size.width - width)/2 ;
double startY = (size.height - height)/2 ;
//直線
for(int i = 0 ; i<=widthCount ; i++){
double dx = (startX + gridSize*i) ;
double dy = startY ;
path.moveTo(dx, dy) ;
path.lineTo(dx, dy+height) ;
}
//橫線
for(int i = 0 ; i<=heightCount; i++){
double dx = startX ;
double dy = startY+gridSize*i ;
path.moveTo(dx, dy) ;
path.lineTo(dx+width, dy) ;
}
canvas.drawPath(path, _paint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
// TODO: implement shouldRepaint
return false ;
}
}
範例圖示
@override
void paint(Canvas canvas, Size size) {
_paint.color = Colors.blueGrey;
_paint.style = PaintingStyle.stroke ;
Path path = Path();
+ Path dotted = Path();
gridSize = size.height/heightCount ;
//直線
double width = gridSize*widthCount;
double height = gridSize*heightCount ;
double startX = (size.width - width)/2 ;
double startY = (size.height - height)/2 ;
for(int i = 0 ; i<=widthCount ; i++){
double dx = (startX + gridSize*i) ;
double dy = startY ;
path.moveTo(dx, dy) ;
path.lineTo(dx, dy+height) ;
//虛線
+ if(i != widthCount){//把起始位置移動到半格的位置
dx = startX+ gridSize*0.5 + gridSize*i ;
dy = startY ;
dotted.moveTo(dx, dy);
dotted.lineTo(dx, dy+height) ;
}
}
//橫線
for(int i = 0 ; i<=heightCount; i++){
double dx = startX ;
double dy = startY+gridSize*i ;
path.moveTo(dx, dy) ;
path.lineTo(dx+width, dy) ;
+ if(i != heightCount){
dx = startX ;
dy = startY+gridSize*0.5+gridSize*i ;
dotted.moveTo(dx, dy);
dotted.lineTo(dx+width, dy) ;
}
}
canvas.drawPath(path, _paint);
canvas.drawPath(dashPath(dotted, dashArray: CircularIntervalList<double>(<double>[4, 4])), _paint) ;//CircularIntervalList [4,4] 4像素實線 ,4像素空格
}