Flutter入门实践

005.2 flutter绘制各种自定义形状【入门篇】

2020-03-07  本文已影响0人  码农二哥

1 CustomPainter是系统的一个类,自定义一个它的子类

import 'dart:math';

import 'package:flutter/material.dart';

class ShapesPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint();
    
    // draw rect
    paint.color = Colors.cyan;
    var rect = Rect.fromLTWH(0, 0, size.width, size.height);
    canvas.drawRect(rect, paint);


    // draw path
    paint.color = Colors.yellow;
    var path = Path();
    path.lineTo(0, size.height);
    path.lineTo(size.width, 0);
    path.close();
    canvas.drawPath(path, paint);


    // draw circle
    paint.color = Colors.deepOrange;
    var center = Offset(size.width / 2, size.height / 2);
    canvas.drawCircle(center, 75.0, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    // just return false for test
    return false;
  }
  
}

2 使用ShapesPainter类

Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Padding(padding: EdgeInsets.all(8.0),
        child: CustomPaint(
          painter: ShapesPainter(),
          child: Container(height: 700,),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );

3 效果

Simulator Screen Shot - iPhone 11 Pro Max - 2020-03-07 at 23.43.33.png
上一篇 下一篇

猜你喜欢

热点阅读