如何在指针向下事件的位置绘制CustomPaint小部件?

时间:2017-10-05 15:37:44

标签: flutter

我正在尝试创建一个简单的小部件,以便当用户按下屏幕时,该位置会出现一个圆圈。我有一个由Listener小部件包装的CustomPaint小部件,如下所示:

              new Listener(
                onPointerDown: down,
                child: new CustomPaint(
                  painter: painter,
                  size: Size.infinite,
                ),
              )

问题是指针向下事件是在全局坐标中提供的,并且绘制是在CustomPaint小部件的本地坐标中完成的。我该如何转换这两个坐标系?

This page说我可以使用RenderBox.globalToLocal方法但是如何获取CustomPaint小部件的RenderBox?

2 个答案:

答案 0 :(得分:3)

您不一定要将侦听器包装在窗口小部件中。您还可以使用GlobalKey获取RenderObject

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  State createState() => new MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
  GlobalKey _paintKey = new GlobalKey();
  Offset _offset;

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('CustomPaint example'),
      ),
      body: new Listener(
        onPointerDown: (PointerDownEvent event) {
          RenderBox referenceBox = _paintKey.currentContext.findRenderObject();
          Offset offset = referenceBox.globalToLocal(event.position);
          setState(() {
            _offset = offset;
          });
        },
        child: new CustomPaint(
          key: _paintKey,
          painter: new MyCustomPainter(_offset),
          child: new ConstrainedBox(
            constraints: new BoxConstraints.expand(),
          ),
        ),
      ),
    );
  }

}

class MyCustomPainter extends CustomPainter {
  final Offset _offset;
  MyCustomPainter(this._offset);

  @override
  void paint(Canvas canvas, Size size) {
    if (_offset == null) return;
    canvas.drawCircle(_offset, 10.0, new Paint()..color = Colors.blue);
  }

  @override
  bool shouldRepaint(MyCustomPainter other) => other._offset != _offset;
}

答案 1 :(得分:0)

好的,这对我有用(感谢@mikemimik对gitter的帮助):

将侦听器包装在扩展StatelessWidget的新自定义窗口小部件中。然后该小部件的build()方法可以像这样访问RenderBox:

  @override
  Widget build(BuildContext context) {
    void down(PointerDownEvent evt) {
      RenderBox box = context.findRenderObject();
      painter.addPos(box.globalToLocal(evt.position));
    }

    return new Listener(
      onPointerDown: down,
      child: new CustomPaint(
        painter: painter,
        size: Size.infinite,
      ),
    );
  }