Flutter入门系列-自定义Paint

此博客展示了如何利用Flutter的CustomPaint widget结合AnimatedPainter类创建一个自定义的动画圆圈。通过初始化AnimationController和Tween,实现了圆圈大小随时间变化的动画效果,同时在CustomPaint的foregroundPainter中定义了绘制逻辑。
摘要由CSDN通过智能技术生成
//customPaint widget
//foregroundPaint CustomPainter的实现类
//在子类中canvas和paint配合进行原的绘制

class CustomCirclePage extends StatefulWidget {
  @override
  _CustomCirclePageState createState() => _CustomCirclePageState();
}

class _CustomCirclePageState extends State<CustomCirclePage> with SingleTickerProviderStateMixin {
  AnimationController _controller;
  Animation _animation;

  @override
  void initState() {
    super.initState();
    _controller = new AnimationController(vsync: this, duration: Duration(seconds: 3));
    _animation = Tween<double>(begin: 0.0, end: 100.0).animate(_controller);
      // ..addListener(() {
      //   setState(() {});
      // });
    _controller.repeat();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('自绘Circle'),
        ),
        body: Container(
          child: Center(
            child: Container(
              width: 200,
              height: 200,
              color: Colors.blue,
              child: CustomPaint(
                size: Size(200, 200),
                foregroundPainter: AnimatedPainter(_animation),
              ),
            ),
          ),
        ));
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }
}

class AnimatedPainter extends CustomPainter {
  Paint _paint = Paint()
    ..color = Colors.redAccent
    ..strokeWidth = 4
    ..style = PaintingStyle.stroke;

  Animation animation;

  AnimatedPainter(this.animation);

  @override
  void paint(Canvas canvas, Size size) {
    // 这里的offset是以自定义控件的左上角位置为零点位置进行偏移的
    canvas.drawCircle(Offset(100, 100), animation.value * 1.0, _paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}

步骤:

1. 利用 CustomPaint 构建需要绘制的对象,构造方法中的 foregroundPainter 用于接收自定义Painter。

2. 定义继承抽象类 CustomPainter 类的 AnimatedPainter 类,实现 shouldRepaint 方法和 paint 方法,paint 方法中有 Canvas 参数对象,利用该对象可以进行想要的任何绘制操作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值