? ? ? ?看flutter实战,既然实战就得动手,今天使用flutter来绘制五子棋,加深对自定义widget及flutter绘制原理的认识,本列子来自flutter实战。
import 'package:flutter/material.dart';
import 'package:fluttertest/CustomPaintRoute.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const CustomPaintRoute(),
);
}
}
import 'package:flutter/material.dart';
import 'package:fluttertest/qipan.dart';
import 'package:fluttertest/qizi.dart';
class CustomPaintRoute extends StatelessWidget {
const CustomPaintRoute({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
RepaintBoundary(
child: Container(
child: CustomPaint(
foregroundPainter: QiZi(),
size: Size(300,300),
painter: QiPan(),
),
),
),
ElevatedButton(onPressed: (){
setState(){
}
}, child: Text("刷新"))
],
),
);
}
}
import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class QiPan extends CustomPainter{
@override
void paint(Canvas canvas, Size size) {
print('paint');
var rect = Offset.zero&size;
drawChessboard(canvas,rect);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return false;
}
void drawChessboard(Canvas canvas, Rect rect) {
var paint= Paint()
..isAntiAlias=true
..style=PaintingStyle.fill
..color=Color(0xFFDCC48C);
canvas.drawRect(rect, paint);
paint..color=Colors.black38
..style=PaintingStyle.stroke
..strokeWidth=1;
for(int i=0;i<=15;i++){
double dy=rect.top+rect.height/15*i;
canvas.drawLine(Offset(rect.left,dy), Offset(rect.right,dy), paint);
}
for(int i=0;i<=15;i++){
double dx=rect.left+rect.width/15*i;
canvas.drawLine(Offset(dx,rect.top), Offset(dx,rect.bottom), paint);
}
}
}
import 'dart:math';
import 'package:flutter/material.dart';
class QiZi extends CustomPainter{
@override
void paint(Canvas canvas, Size size) {
var rect = Offset.zero&size;
drawPieces(canvas,rect);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return false;
}
void drawPieces(Canvas canvas, Rect rect) {
double _width=rect.width/15;
double _height=rect.height/15;
var paint = Paint()
..style=PaintingStyle.fill
..color=Colors.black;
canvas.drawCircle(Offset(rect.center.dx-_width/2, rect.center.dy-_height/2), min(_width/2,_height/2)-2, paint);
paint..color=Colors.white;
canvas.drawCircle(Offset(rect.center.dx+_width/2, rect.center.dy+_height/2), min(_width/2,_height/2)-2, paint);
}
}
????????
|