Flutter之Align

1、Align介绍

Align的作为一个参数,设置子child的对齐方式,比如居中,左上,右下等多个对齐方向

2、部分源码和功能

  const Align({
    Key key,
    this.alignment = Alignment.center,
    this.widthFactor,
    this.heightFactor,
    Widget child,
  }) : assert(alignment != null),
       assert(widthFactor == null || widthFactor >= 0.0),
       assert(heightFactor == null || heightFactor >= 0.0),
       super(key: key, child: child);
  
  /// The top left corner.
  static const Alignment topLeft = Alignment(-1.0, -1.0);

  /// The center point along the top edge.
  static const Alignment topCenter = Alignment(0.0, -1.0);

  /// The top right corner.
  static const Alignment topRight = Alignment(1.0, -1.0);

  /// The center point along the left edge.
  static const Alignment centerLeft = Alignment(-1.0, 0.0);

  /// The center point, both horizontally and vertically.
  static const Alignment center = Alignment(0.0, 0.0);

  /// The center point along the right edge.
  static const Alignment centerRight = Alignment(1.0, 0.0);

  /// The bottom left corner.
  static const Alignment bottomLeft = Alignment(-1.0, 1.0);

  /// The center point along the bottom edge.
  static const Alignment bottomCenter = Alignment(0.0, 1.0);

  /// The bottom right corner.
  static const Alignment bottomRight = Alignment(1.0, 1.0);

我们知道最左上角的坐标是Alignment(-1.0, -1.0),中心坐标是Alignment(0.0, 0.0);然后最右下角坐标是Alignment(1.0, 1.0);

FractionalOffset对其封装了大小范围是(0~1),FractionalOffset(0, 0)对于左上角,FractionalOffset(1, 1)对于右下角,FractionalOffset(0.5, 0.5)对于中间坐标

FractionalOffset(0.5, 0.5) == Alignment(0.0,0.0) == Alignment.center

3、测试代码

测试1

  @override
  Widget build(BuildContext context) {
      return MaterialApp(
          title: 'open url',
          home: Scaffold(
            appBar: AppBar(
              // Here we take the value from the MyHomePage object that was created by
              // the App.build method, and use it to set our appbar title.
              title: Text('hello flutter'),
            ),
            body: Align(
              alignment: FractionalOffset(1, 0),
              child: Container(
                  color: Colors.red,
                  width: 100,
                  height: 100,
              ),
            ),
          ),
      );
  }

测试2

  @override
  Widget build(BuildContext context) {
      return MaterialApp(
          title: 'open url',
          home: Scaffold(
            appBar: AppBar(
              // Here we take the value from the MyHomePage object that was created by
              // the App.build method, and use it to set our appbar title.
              title: Text('hello flutter'),
            ),
            body: Align(
              alignment: FractionalOffset(0.5, 0),
              child: Text("chenyu"),
            ),
          ),
      );
  }
}

4、运行效果

测试1结果

项目结构如下

测试2结果

(0)

相关推荐