Flutter源码解读

FittedBox

2022-03-18  本文已影响0人  NetWork小贱

一、源码解读

//  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(
  alignment: Alignment.centerLeft,
  fit: BoxFit.fill,
  child: Container(
    height: 100,
    width: 60,
    color: Colors.red,
    child: Text('我是一种大大大'),
  ),
)
上一篇 下一篇

猜你喜欢

热点阅读