Flutter:FittedBox(缩放布局)

FittedBox 组件主要做两件事,缩放(Scale)和位置调整(Position)。
FittedBox 会在自己的尺寸范围内缩放并调整 child 的位置,使 child 适合其尺寸。FittedBox 和 Android 中的 ImageView 有些类似,将图片在其范围内按照规则进行缩放和位置调整。

布局分为两种情况:

如果外部有约束的话,按照外部约束调整自身尺寸,然后缩放调整 child ,按照指定条件进行布局。

如果没有外部约束条件,则跟 child 尺寸一样,指定的缩放和位置属性将不起作用。

有 fit 和 alignment 两个属性。

fit:缩放的方式,默认属性是 BoxFit.contain,child 在 FittedBox范围内,尽可能大,但是不超过其尺寸。contain 是在保持着 child 宽高比的大前提下,尽可能填满。一般情况下,宽度和高度达到最大值时,就会停止缩放。

  • BoxFit.none,没有任何填充模式,如下
    在这里插入图片描述
  • BoxFit.fill:不按宽高比例填充,内容不会超过容器范围
    在这里插入图片描述
  • BoxFit.contain:按照宽高比等比模式填充,内容不会超过容器范围
    在这里插入图片描述
  • BoxFit.cover:按照原始尺寸填充整个容器模式。内容可能回超过容器范围
    在这里插入图片描述
  • BoxFit.scaleDown:会根据情况缩小范围
    在这里插入图片描述

alignment:设置对齐方式,默认属性是 Aligment.center,居中显示 child。

具体示例代码如下:


class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '布局示例',
      home: LayoutDemo(),
    );
  }
}

class LayoutDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: Text('Center'),
      ),
      body: Container(
        width: 250,
        height: 250,
        color: Colors.grey,
        child: FittedBox(
          fit: BoxFit.scaleDown,
          alignment: Alignment.topLeft,
          child: Container(
            color: Colors.deepOrange,
            child: Text('缩放布局'),
          ),
        ),
      ),
    );
  }
}

发布了119 篇原创文章 · 获赞 28 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/ldxlz224/article/details/102701317