使用photoview显示图像的特定部分(basePosition和initialScale)

时间:2020-04-22 19:46:28

标签: image flutter

我想显示图像的某些部分。我开始使用photoview库,因为您可以设置basePosition和initialScale。

因此,我在图像内定义了一个矩形:左上角位置,宽度和高度。 (contentPosX,contentPosY,contentWidth,contentHeight)

我有一个带有特定部分(右侧蘑菇)的图像:

enter image description here 我计算矩形的中心(匹配值范围[-1; 1]):

double alignmentX = ((contentPosX + contentWidth / 2) / imageWidth) * 2 - 1;
double alignmentY = ((contentPosY + contentHeight / 2) / imageHeight) * 2 - 1;

还有缩放系数:

double zoom = imageHeight / contentHeight;

正如您在下面看到的那样,我没有得到预期的结果。这有点转移了。我想念什么? 我不依赖于photoview库,如果有其他方法可以解决此问题,欢迎您!

enter image description here

这是我的代码中有效的虚拟部分:

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Photoview problem"),
      ),
      body: StaggeredGridView.countBuilder(
        crossAxisCount: 2,
        itemCount: 1,
        itemBuilder: (BuildContext context, int index) => _buildGridItem(context, index),
        staggeredTileBuilder: (int index) {
          final imageWidth = 2048;
          final imageHeight = 1536;
          final contentPosX = 1067;
          final contentPosY = 275;
          final contentWidth = 766;
          final contentHeight = 820;
          return StaggeredTile.count(1, contentHeight / contentWidth);
        },
      ),
    );
  }

  Widget _buildGridItem(BuildContext context, int index) {
    final imageWidth = 2048;
    final imageHeight = 1536;
    final contentPosX = 1067;
    final contentPosY = 275;
    final contentWidth = 766;
    final contentHeight = 820;
    double zoom = imageHeight / contentHeight;
    double alignmentX = ((contentPosX + contentWidth / 2) / imageWidth) * 2 - 1;
    double alignmentY = ((contentPosY + contentHeight / 2) / imageHeight) * 2 - 1;
    return ClipRect(
      child: PhotoView(
        basePosition: Alignment(alignmentX, alignmentY),
        initialScale: PhotoViewComputedScale.covered * zoom,
        imageProvider: AssetImage('assets/image.jpg'),
      ),
    );
  }
}

0 个答案:

没有答案