在Flutter中,绘图需要用到 CustomPaint 和 CustomPainter, 绘制基本图片包括点、线、矩形(正方形、长方形)、弧、椭圆等等,绘制功能需要结合CustomPaint 和 CustomPainter来实现,本文章来实现绘制椭圆功能。 测试页面启动函数 void main() { ///启动根目录 runApp(MaterialApp( home: Example808(), )); }
测试页面主内容,CustomPaint 中 属性 painter 来配置的绘制椭圆与圆形的核心代码: class Example808 extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("绘制圆形"), ), backgroundColor: Colors.grey, body: Container( width: MediaQuery.of(context).size.width, color: Colors.white, //创建画板 child: CustomPaint( //指定画布大小 size: const Size(400, 400), painter: CirclePainter(), ), ), ); } }
通过canvas的drawCircle可实现绘制实心圆或者是圆环,基本绘制代码如下: class CirclePainter extends CustomPainter { //[定义画笔] final Paint _paint = Paint() ..color = Colors.blue ..style= PaintingStyle.stroke ..strokeWidth = 4.0;
@override void paint(Canvas canvas, Size size) { //参数一 圆心的中心点位置 //参数二 半径大小 canvas.drawCircle(const Offset(100,100), 40, _paint);
} @override bool shouldRepaint(CustomPainter oldDelegate) { return true; } }
配置画笔Paint的style为PaintingStyle.fill模式,绘制的是实心圆,PaintingStyle.stroke模式为绘制的圆环。 绘制椭圆首先需要定义一个矩形Rect,然后再绘制这个矩形的内切圆,如果这个矩形正好是个正方形,那么绘制出来的椭圆也就是个圆形,通过canvas的drawOval方法来绘制一个椭圆,如下图所示: ![](http://image109.360doc.com/DownloadImg/2022/12/1509/257543692_1_20221215090044117_wm.png)
绘制椭圆核心绘制代码如下: class OvalPainter extends CustomPainter { //[定义画笔] final Paint _paint = Paint() ..color = Colors.blue ..style = PaintingStyle.stroke ..strokeWidth = 4.0;
@override void paint(Canvas canvas, Size size) { //用Rect构建一个边长50,中心点坐标为100,100的矩形 Rect rect = Rect.fromCircle( center: const Offset(100.0, 100.0), radius: 40.0, ); //绘制椭圆 canvas.drawOval(rect, _paint);
//使用两个对角点来创建width为150 height为100的矩形 Rect rect2 = Rect.fromPoints( const Offset(200, 50), const Offset(350, 150), ); //绘制椭圆 canvas.drawOval(rect2, _paint); }
@override bool shouldRepaint(CustomPainter oldDelegate) { return true; } }
|