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('縮放佈局'),
),
),
),
);
}
}