一、源碼解讀
// FittedBox 繼承于 SingleChildRenderObjectWidget
class FittedBox extends SingleChildRenderObjectWidget {
/// 創建一個根據 fit 在其內部縮放和定位子組件的組件
const FittedBox({
Key? key,
this.fit = BoxFit.contain,
this.alignment = Alignment.center,
this.clipBehavior = Clip.none,
Widget? child,
}) : assert(fit != null),
assert(alignment != null),
assert(clipBehavior != null),
super(key: key, child: child);
/// 設置將子組件在父組件中分配形式
/// BoxFit 的簡介:
/// fill : 通過扭曲源的縱橫比,來填充父空間
/// contain: 不改變源的縱橫比,盡可能大的填充父空間
/// cover: 顯示可能拉伸,可能裁剪,以最小區域充滿父空間(可能是源的某部分)
/// fitWidth: 確保顯示源的全寬,無論這是否意味著源垂直溢出目標框。
/// fitHeight: 確保顯示源的全高,無論這是否意味著源水平溢出目標框。
/// none: 在目標框內對齊源(默認情況下,居中)并丟棄源中位于框外的任何部分。
/// scaleDown: 在目標框中對齊源(默認情況下,居中),如果必要,縮小源以確保源適合框。
final BoxFit fit;
/// 設置子組件在父組件內的對齊方式
final AlignmentGeometry alignment;
/// 裁剪的形似,包括(none: 不裁剪;hardEdge:裁剪,不使用抗鋸齒;antiAlias:裁剪,使用抗鋸齒;antiAliasWithSaveLayer: 使用抗鋸齒同時使用 saveLayer 裁剪)
final Clip clipBehavior;
/// 創建渲染對象 RenderFittedBox
@override
RenderFittedBox createRenderObject(BuildContext context) {
return RenderFittedBox(
fit: fit,
alignment: alignment,
// 獲取系統文字方向
textDirection: Directionality.maybeOf(context),
clipBehavior: clipBehavior,
);
}
/// 更新渲染對象的參數
@override
void updateRenderObject(BuildContext context, RenderFittedBox renderObject) {
renderObject
..fit = fit
..alignment = alignment
..textDirection = Directionality.maybeOf(context)
..clipBehavior = clipBehavior;
}
/// Debug 模式,屬性的填充
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(EnumProperty<BoxFit>('fit', fit));
properties.add(DiagnosticsProperty<AlignmentGeometry>('alignment', alignment));
}
}
二、 總結
- FittedBox 主要是 fit 參數,該參數決定子組件在父組件中的渲染展示形式
- FittedBox 的子組件的定位是有參數 alignment 決定的,默認居中。
三、實例
FittedBox(
alignment: Alignment.centerLeft,
fit: BoxFit.fill,
child: Container(
height: 100,
width: 60,
color: Colors.red,
child: Text('我是一種大大大'),
),
)