Flutter:平移,旋转和缩放堆栈中的已定位小部件

时间:2020-06-10 21:47:41

标签: flutter dart

我正在尝试无缝移动,旋转和缩放放置在堆栈中的小部件。由于“平移和缩放”手势识别器无法在GestureDetector小部件中一起使用,因此我尝试使用缩放来导出偏移量。

但是,尝试同时平移和缩放时,对象会以奇怪的方式缩放,并且对象会缩放并移开我的手指。如果分开进行,它们将表现正常。

基于几篇文章,我尝试了以下操作:

    import 'package:app/features/_shared_widgets/vertical_spacing.dart';
    import 'package:app/model/piece.dart';
    import 'package:flutter/material.dart';
    import 'package:transparent_image/transparent_image.dart';
    import 'dart:ui' as ui;

    class MoveableStackItem extends StatefulWidget {
      final Piece piece;
      MoveableStackItem({@required this.piece});

      @override
      State<StatefulWidget> createState() {
        return _MoveableStackItemState();
      }
    }

    class _MoveableStackItemState extends State<MoveableStackItem> {
      double _xPosition;
      double _yPosition;
      double _rotation;
      double _scale;

      Offset _startingFocalPoint;
      Offset _previousOffset;
      double _previousScale;

      @override
      void initState() {
        super.initState();

    _xPosition = widget.piece.position.x;
    _yPosition = widget.piece.position.y;
    _rotation = widget.piece.position.angle;
    _scale = widget.piece.position.scale;
  }

  @override
  Widget build(BuildContext context) {
    return Positioned(
      top: _yPosition,
      left: _xPosition,
      child: GestureDetector(
        onScaleStart: (ScaleStartDetails details) {
          setState(() {
            _startingFocalPoint = details.focalPoint;
            _previousOffset = Offset(_xPosition, _yPosition);
            _previousScale = _scale;
          });
        },
        onScaleUpdate: (ScaleUpdateDetails details) {
          setState(() {
            _scale = _previousScale * details.scale;

            // Ensure that item under the focal point stays in the same place despite zooming
            final Offset normalizedOffset =
                (_startingFocalPoint - _previousOffset) / _previousScale;
            _xPosition = (details.focalPoint - normalizedOffset * _scale).dx;
            _yPosition = (details.focalPoint - normalizedOffset * _scale).dy;
            if (details.rotation != 0) _rotation = details.rotation;
          });
        },
        child: Transform.rotate(
          angle: _rotation,
          child: Transform.scale(
            scale: _scale,
            child: Container(
              width: 200,
              child: FadeInImage.memoryNetwork(
                fit: BoxFit.contain,
                image: widget.piece.imageUrl,
                placeholder: kTransparentImage,
                placeholderErrorBuilder: (context, url, error) =>
                    Icon(Icons.error),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

我还尝试了Transform.translate的顶部位置:0,左侧位置:0,结果相同。有人能检测到可能使翻译不满意的任何内容吗?

0 个答案:

没有答案