自定义画家中图像上的单击事件

问题描述 投票:0回答:1

我正在尝试单击我的drawImage,但如何实现它我不知道我提供了下面的代码。

class MyApp extends StatelessWidget {
  MyApp({super.key});

  final ValueNotifier<ui.Offset> onTappedLocation =
      ValueNotifier(ui.Offset.zero);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      debugShowCheckedModeBanner: false,
      home: Container(
        color: Colors.indigo,
        child: GestureDetector(
          onTapDown: (details) {
            onTappedLocation.value = details.globalPosition;
          },
          child: Center(
              child: FutureBuilder<ui.Image>(
                  future: getImage(),
                  builder:
                      (BuildContext context, AsyncSnapshot<ui.Image> snapshot) {
                    Widget centerChild;
                    if (snapshot.hasData) {
                      centerChild = CustomPaint(
                        painter: FootballPitchPainter(
                            snapshot.data!, onTappedLocation, () {
                          print("object");
                        }),
                        size: Size(360, 480),
                      );
                    } else {
                      centerChild = const CircularProgressIndicator();
                    }
                    return centerChild;
                  })),
        ),
      ),
    );
  }
}

class FootballPitchPainter extends CustomPainter {
  final ui.Image? image;
  ValueNotifier<ui.Offset> onTappedLocation;
  VoidCallback onTap;

  FootballPitchPainter(this.image, this.onTappedLocation, this.onTap)
      : super(repaint: onTappedLocation);

  @override
  void paint(Canvas canvas, Size size) {
    final w = size.width;
    final h = size.height;

    // Other Code

    canvas.drawImage(image!, ui.Offset(100, 100), playerPaint);
    if (onTappedLocation.value == ui.Offset(100, 100)) {
      onTap();
    }
  }

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

Future<ui.Image> getImage() async {
  ByteData bd = await rootBundle.load('assets/logo.png');
  final Uint8List bytes = Uint8List.view(bd.buffer);
  final ui.Codec codec =
      await ui.instantiateImageCodec(bytes, targetHeight: 20, targetWidth: 20);
  final ui.Image image = (await codec.getNextFrame()).image;
  return image;
}

我尝试通过手势检测器来实现它,但是我在 localPosition 和 globalPoistion 上获得的位置与自定义画家偏移位置不同,所以我无法实现它。

android flutter mobile custom-painter
1个回答
0
投票

您可以通过将任何小部件包装在 GestureDetectorInkWell 中来检测它们的点击。

所以在你的 MyApps 构建方法中你可以有类似的东西:

...
Center(
  child: GestureDetector(
    onTap: () {
      // Your action
    },
    child: FutureBuilder<...

您可能还想使用更专业的小部件,例如 NetworkImageAssetImage 来加载图像。

© www.soinside.com 2019 - 2024. All rights reserved.