如何在内部圆圈不离开外部圆圈的颤动中制作操纵杆?

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

我正在尝试在颤振中创建操纵杆,但是我无法以适当的方式将内圆限制在外圆内,对此有什么建议吗?外圆也可以设置一个图片作为背景..我尝试使用一定范围的偏移量限制它,但是我不确定这是否是正确的方法.....这是我的代码。

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: JoyStick(),
  ));
}

class JoyStick extends StatefulWidget {
  @override
  _JoyStickState createState() => _JoyStickState();
}

class _JoyStickState extends State<JoyStick> {
  Offset offset, smallCircleOffset;
  @override
  void initState() {
    offset = Offset(0, 0);
    smallCircleOffset = offset;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: <Widget>[
          Container(
            color: Colors.lightBlue,
            height: MediaQuery.of(context).size.height,
            width: MediaQuery.of(context).size.width,
          ),
          CustomPaint(
            painter: Painter(false, this.offset,false),
            child: CustomPaint(
              painter: Painter(true, smallCircleOffset,(true)),
            ),
          ),
          GestureDetector(
            onPanEnd: (details){
              setState(() {
                smallCircleOffset = offset;
              });

            },
            onPanUpdate: (details) {
              setState(() {
                RenderBox renderBox = context.findRenderObject();
                smallCircleOffset = renderBox.globalToLocal(details.globalPosition);

              },
              );

            },

          ),
        ],
      ),
    );
  }
}

class Painter extends CustomPainter {
  final bool needsRepaint,isInBoundary;
  final Offset offset;
  Painter(this.needsRepaint, this.offset, this.isInBoundary);
  @override
  void paint(Canvas canvas, Size size) {
    if (needsRepaint && isInBoundary) {
      print("Offset for smaller circle  = $offset with distance squared = ${offset.distanceSquared} \n and distance = ${offset.distance}");
      canvas.drawCircle(this.offset, 50, Paint()..color = Colors.amber);
    } else {
      canvas.drawCircle(this.offset, 200, Paint()..color = Colors.black);

    }
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return (needsRepaint && isInBoundary)?true:false;

  }
}
android ios flutter canvas view
1个回答
0
投票

在您的onPanUpdate()方法中,仅当偏移距离小于200时才调用setState,如下所示:

            onPanUpdate: (details) {
              if(smallCircleOffset.distance < 200){
                setState(() {
                  RenderBox renderBox = context.findRenderObject();
                  smallCircleOffset = renderBox.globalToLocal(details.globalPosition);
                });
              } 

            },

[如果想要在平移内圆之后在圆内移动的适当操纵杆,请尝试在Flutter中使用The Control Pad package。它提供了一个操纵杆,并提供了很多选择。

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