FittedBox

一、源碼解讀

//  FittedBox 繼承于 SingleChildRenderObjectWidget 
class FittedBox extends SingleChildRenderObjectWidget {
  /// 創(chuàng)建一個(gè)根據(jù) fit 在其內(nèi)部縮放和定位子組件的組件
  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);

  ///  設(shè)置將子組件在父組件中分配形式
  /// BoxFit 的簡介:
  /// fill : 通過扭曲源的縱橫比,來填充父空間
  /// contain: 不改變?cè)吹目v橫比,盡可能大的填充父空間
  /// cover:  顯示可能拉伸,可能裁剪,以最小區(qū)域充滿父空間(可能是源的某部分)
  /// fitWidth: 確保顯示源的全寬,無論這是否意味著源垂直溢出目標(biāo)框。
  /// fitHeight: 確保顯示源的全高,無論這是否意味著源水平溢出目標(biāo)框。
  /// none: 在目標(biāo)框內(nèi)對(duì)齊源(默認(rèn)情況下,居中)并丟棄源中位于框外的任何部分。
  /// scaleDown: 在目標(biāo)框中對(duì)齊源(默認(rèn)情況下,居中),如果必要,縮小源以確保源適合框。
  final BoxFit fit;

  ///  設(shè)置子組件在父組件內(nèi)的對(duì)齊方式
  final AlignmentGeometry alignment;

  /// 裁剪的形似,包括(none: 不裁剪;hardEdge:裁剪,不使用抗鋸齒;antiAlias:裁剪,使用抗鋸齒;antiAliasWithSaveLayer: 使用抗鋸齒同時(shí)使用 saveLayer 裁剪)
  final Clip clipBehavior;
  
  /// 創(chuàng)建渲染對(duì)象 RenderFittedBox
  @override
  RenderFittedBox createRenderObject(BuildContext context) {
    return RenderFittedBox(
      fit: fit,
      alignment: alignment,
      // 獲取系統(tǒng)文字方向
      textDirection: Directionality.maybeOf(context), 
      clipBehavior: clipBehavior,
    );
  }
  
  /// 更新渲染對(duì)象的參數(shù)
  @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));
  }
}

二、 總結(jié)

  • FittedBox 主要是 fit 參數(shù),該參數(shù)決定子組件在父組件中的渲染展示形式
  • FittedBox 的子組件的定位是有參數(shù) alignment 決定的,默認(rèn)居中。

三、實(shí)例

FittedBox(
  alignment: Alignment.centerLeft,
  fit: BoxFit.fill,
  child: Container(
    height: 100,
    width: 60,
    color: Colors.red,
    child: Text('我是一種大大大'),
  ),
)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容