gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:40:54 35 4
gpt4 key购买 nike

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

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

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

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

最佳答案

您不一定必须将监听器包装在小部件中。您还可以使用 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;
}

关于flutter - 如何在指针向下事件的位置绘制 CustomPaint 小部件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46589633/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com