Flutter 实现按位置大小比例布局的控件

文章目录

  • 前言
  • 一、如何实现?
    • 1、数值转成分数
    • 2、Row+Flexible布局横向
    • 3、Column+Flexible布局纵向
  • 二、完整代码
  • 三、使用示例
    • 1、基本用法
    • 2、四分屏
    • 3、六分屏
    • 4、八分屏
    • 5、九分屏
    • 6、414分屏
  • 总结


前言

做视频监控项目时需要需要展示多分屏,比如2x2、3x3、414等等,如果每一种分屏都单独实现会很麻烦,而且不能支持用户定制。最好的方式还是实现一个通用的分屏容器,而且采样比例计算位置大小,可以适配任意尺寸。


一、如何实现?

最直观的实现方式是获取控件宽高然后按比例计算,但是flutter在build的时候无法获取位置宽高信息,只有绘制之后才能获取,所以这种方式并不容易实现,比较简单的方式应该是使用Row、Column结合Flexible。

1、数值转成分数

需要转换的数值

 final Rect rect; //子控件位置大小,比例值范围0-1

定义一个分数对象

//分数
class Rational {
  int den = 1; //分母
  int num = 0; //分子
  Rational(this.num, this.den);
  //通过double构造,accuracy小数点后精度
  factory Rational.fromDouble(double d, {int accuracy = 5}) {
    int den = 1;
    while (d > d.toInt() && accuracy-- > 0) {
      d *= 10;
      den *= 10;
    }
    return Rational(d.toInt(), den);
  }
}

转成分数并对齐分母

    //将位置大小转成分数
    final width = Rational.fromDouble(rect.width);
    final x = Rational.fromDouble(rect.left);
    final height = Rational.fromDouble(rect.height);
    final y = Rational.fromDouble(rect.top);
    //对齐分母
    if (width.den != x.den) {
      final den = width.den;
      width.den *= x.den;
      width.num *= x.den;
      x.den *= den;
      x.num *= den;
    }
    //对齐分母
    if (height.den != y.den) {
      final den = height.den;
      height.den *= y.den;
      height.num *= y.den;
      y.den *= den;
      y.num *= den;
    }

2、Row+Flexible布局横向

我们利用Row的自动布局,以及Flexible的比例布局的特性,根据上面的分数计算出控件比例的位置大小对应的flex值即可。

 Row(
      children: [
        Flexible(
          flex: x.num,
          child: Container(),
        ),
        Flexible(
          flex: width.num,
          child: child/*子控件,加上纵向布局则是Column*/
        ),
        Flexible(flex: width.den - width.num - x.num, child: Container()),
      ],
    );
  }

3、Column+Flexible布局纵向

我们利用Column的自动布局,以及Flexible的比例布局的特性,根据上面的分数计算出控件比例的位置大小对应的flex值即可。

Column(
            children: [
              Flexible(
                flex: y.num,
                child: Container(),
              ),
              Flexible(flex: height.num, child: child/*子控件*/),
              Flexible(
                flex: height.den - height.num - y.num,
                child: Container(),
              ),
            ],
          )

二、完整代码

proportion.dart

import 'package:flutter/material.dart';

//比例布局控件,
class Proportion extends StatelessWidget {
  final Rect rect; //位置大小,比例值范围0-1
  final Widget child;
  const Proportion({
    super.key,
    this.rect = const Rect.fromLTWH(0, 0, 1, 1),
    required this.child,
  });

  
  Widget build(BuildContext context) {
    //实现按比例显示布局
    final width = Rational.fromDouble(rect.width);
    final x = Rational.fromDouble(rect.left);
    final height = Rational.fromDouble(rect.height);
    final y = Rational.fromDouble(rect.top);
    if (width.den != x.den) {
      final den = width.den;
      width.den *= x.den;
      width.num *= x.den;
      x.den *= den;
      x.num *= den;
    }
    if (height.den != y.den) {
      final den = height.den;
      height.den *= y.den;
      height.num *= y.den;
      y.den *= den;
      y.num *= den;
    }
    return Row(
      children: [
        Flexible(
          flex: x.num,
          child: Container(),
        ),
        Flexible(
          flex: width.num,
          child: Column(
            children: [
              Flexible(
                flex: y.num,
                child: Container(),
              ),
              Flexible(flex: height.num, child: child),
              Flexible(
                flex: height.den - height.num - y.num,
                child: Container(),
              ),
            ],
          ),
        ),
        Flexible(flex: width.den - width.num - x.num, child: Container()),
      ],
    );
  }
}

//分数
class Rational {
  int den = 1; //分母
  int num = 0; //分子
  Rational(this.num, this.den);
  //通过double构造,accuracy小数点后精度
  factory Rational.fromDouble(double d, {int accuracy = 5}) {
    int den = 1;
    while (d > d.toInt() && accuracy-- > 0) {
      d *= 10;
      den *= 10;
    }
    return Rational(d.toInt(), den);
  }
}

常用布局(可选)
proportions.dart

import 'package:flutter/material.dart';

import 'proportion.dart';

//常用布局,需配合stack作为父容器使用
class Proportions {
  Proportions._();
  //全屏
  static List<Proportion> fullScreen({
    required Widget child,
  }) =>
      [
        Proportion(
          rect: const Rect.fromLTWH(0, 0, 1, 1),
          child: child,
        )
      ];

  //二分屏
  static List<Proportion> halfScreen({
    required Widget left,
    required Widget right,
  }) =>
      [
        Proportion(
          rect: const Rect.fromLTWH(0, 0, 0.5, 1),
          child: left,
        ),
        Proportion(
          rect: const Rect.fromLTWH(0.5, 0, 0.5, 1),
          child: right,
        ),
      ];

  //四分屏
  static List<Proportion> quadScreen({
    required List<Widget> children,
  }) {
    return [
      Proportion(
        rect: const Rect.fromLTWH(0, 0, 0.5, 0.5),
        child: children[0],
      ), //左上
      Proportion(
        rect: const Rect.fromLTWH(0.5, 0, 0.5, 0.5),
        child: children[1],
      ), //右上
      Proportion(
        rect: const Rect.fromLTWH(0, 0.5, 0.5, 0.5),
        child: children[2],
      ), //左下
      Proportion(
        rect: const Rect.fromLTWH(0.5, 0.5, 0.5, 0.5),
        child: children[3],
      ), //右下
    ];
  }

  //6  分屏
  static List<Proportion> sixScreen({
    required List<Widget> children,
  }) {
    return [
      Proportion(
        rect: const Rect.fromLTWH(0, 0, 0.666, 0.666),
        child: children[0],
      ), //左上
      Proportion(
        rect: const Rect.fromLTWH(0.666, 0, 0.333, 0.333),
        child: children[1],
      ), //右上
      Proportion(
        rect: const Rect.fromLTWH(0.666, 0.333, 0.333, 0.333),
        child: children[2],
      ), //右中
      Proportion(
        rect: const Rect.fromLTWH(0.666, 0.666, 0.333, 0.333),
        child: children[3],
      ), //右下
      Proportion(
        rect: const Rect.fromLTWH(0.333, 0.666, 0.333, 0.333),
        child: children[4],
      ), //中下
      Proportion(
        rect: const Rect.fromLTWH(0, 0.666, 0.333, 0.333),
        child: children[5],
      ), //左下
    ];
  }

  //8  分屏
  static List<Proportion> eightScreen({
    required List<Widget> children,
  }) {
    return [
      Proportion(
        rect: const Rect.fromLTWH(0, 0, 0.75, 0.75),
        child: children[0],
      ), //左上
      Proportion(
        rect: const Rect.fromLTWH(0.75, 0, 0.25, 0.25),
        child: children[1],
      ), //右上
      Proportion(
        rect: const Rect.fromLTWH(0.75, 0.25, 0.25, 0.25),
        child: children[2],
      ), //右中1
      Proportion(
        rect: const Rect.fromLTWH(0.75, 0.5, 0.25, 0.25),
        child: children[3],
      ), //右中2
      Proportion(
        rect: const Rect.fromLTWH(0.75, 0.75, 0.25, 0.25),
        child: children[4],
      ), //右下
      Proportion(
        rect: const Rect.fromLTWH(0.5, 0.75, 0.25, 0.25),
        child: children[5],
      ), //中下2
      Proportion(
        rect: const Rect.fromLTWH(0.25, 0.75, 0.25, 0.25),
        child: children[6],
      ), //中下1
      Proportion(
        rect: const Rect.fromLTWH(0, 0.75, 0.25, 0.25),
        child: children[7],
      ), //左下
    ];
  }

  //9  分屏
  static List<Proportion> nightScreen({
    required List<Widget> children,
  }) {
    int n = 0;
    return [
      ...children.getRange(0, 9).map(
        (element) {
          final i = n++;
          return Proportion(
            rect: Rect.fromLTWH(
              (i % 3) * 0.333,
              (i ~/ 3) * 0.333,
              0.333,
              0.333,
            ),
            child: element,
          );
        },
      )
    ];
  }

  //16  分屏
  static List<Proportion> sixteenScreen({
    required List<Widget> children,
  }) {
    int n = 0;
    return [
      ...children.getRange(0, 16).map(
        (element) {
          final i = n++;
          return Proportion(
            rect: Rect.fromLTWH((i % 4) * 0.25, (i ~/ 4) * 0.25, 0.25, 0.25),
            child: element,
          );
        },
      )
    ];
  }

  //414分屏
  static List<Proportion> fourOneFourScreen({
    required List<Widget> children,
  }) {
    int n = 0;
    return [
      //左4
      ...children.getRange(0, 4).map(
        (element) {
          final i = n++;
          return Proportion(
            rect: Rect.fromLTWH((i ~/ 4) * 0.25, (i % 4) * 0.25, 0.25, 0.25),
            child: element,
          );
        },
      ),
      //中间
      Proportion(
        rect: const Rect.fromLTWH(0.25, 0, 0.5, 1),
        child: children[4],
      ),
      //右边4
      ...children.getRange(5, 9).map(
        (element) {
          final i = n++ + 8;
          return Proportion(
            rect: Rect.fromLTWH((i ~/ 4) * 0.25, (i % 4) * 0.25, 0.25, 0.25),
            child: element,
          );
        },
      )
    ];
  }
}

三、使用示例

1、基本用法

设置子控件位置大小。一般配合stack作为父容器使用

    Proportion(
      rect: Rect.fromLTRB(0, 0, 0.5, 0.5), //子控件位置大小,(0, 0, 0.5, 0.5)表示左上1/4的区域
      child: ColoredBox(color: Colors.red), //子控件
    );

2、四分屏

final List<int> _nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
 Stack(
            children: Proportions.quadScreen(children: [
          ..._nums.map((e) => Container(
                constraints: const BoxConstraints.expand(),
                decoration: BoxDecoration(
                    border: Border.all(color: Colors.deepPurple.shade300)),
                child: Center(child: Text("video $e")),
              ))

在这里插入图片描述

3、六分屏

final List<int> _nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
 Stack(
            children: Proportions.sixScreen(children: [
          ..._nums.map((e) => Container(
                constraints: const BoxConstraints.expand(),
                decoration: BoxDecoration(
                    border: Border.all(color: Colors.deepPurple.shade300)),
                child: Center(child: Text("video $e")),
              ))

在这里插入图片描述

4、八分屏

final List<int> _nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
 Stack(
            children: Proportions.eightScreen(children: [
          ..._nums.map((e) => Container(
                constraints: const BoxConstraints.expand(),
                decoration: BoxDecoration(
                    border: Border.all(color: Colors.deepPurple.shade300)),
                child: Center(child: Text("video $e")),
              ))

在这里插入图片描述

5、九分屏

final List<int> _nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
 Stack(
            children: Proportions.nightScreen(children: [
          ..._nums.map((e) => Container(
                constraints: const BoxConstraints.expand(),
                decoration: BoxDecoration(
                    border: Border.all(color: Colors.deepPurple.shade300)),
                child: Center(child: Text("video $e")),
              ))

在这里插入图片描述

6、414分屏

final List<int> _nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
 Stack(
            children: Proportions.fourOneFourScreen(children: [
          ..._nums.map((e) => Container(
                constraints: const BoxConstraints.expand(),
                decoration: BoxDecoration(
                    border: Border.all(color: Colors.deepPurple.shade300)),
                child: Center(child: Text("video $e")),
              ))

在这里插入图片描述
始终保持比例
在这里插入图片描述


总结

以上就是今天要讲的内容,本文用的是比较简单的方式实现了比例布局控件,其主要特点是可以灵活使用,尤其是方便视频分屏预览的实现。本质上也是对一类布局规则的总结得出的一个通用的控件,因为考虑到2x2、3x3还是可以写死的,但是到了4x4、5x5写死则需要16、25个参数,那就必须改用数组,也就意味着需要根据规则计算位置,那和本文一样了。所以本文的控件是有实际使用意义的。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/61387.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

docker安装MinIO

简介 Minio 是一个面向对象的简单高性能存储服务。使用 Go 语言编写&#xff0c;性能高、具有跨平台性。 Minio 官网为&#xff1a;https://min.io &#xff0c;有一个中文站点&#xff0c;单内容更新不是很及时&#xff0c;建议从原始官网学习。 本文采用 Docker 安装&…

grid map学习笔记3之详解grid_map_pcl库实现point cloud点云转换成grid map栅格地图

文章目录 0 引言1 grid_map_pcl示例1.1 主要文件1.2 示例数据1.3 启动文件1.4 配置文件1.5 主要实现流程1.6 启动示例1.7 示例结果 2 D435i 点云生成栅格地图2.1 D435i 点云文件2.2 修改启动文件2.3 测试和结果2.4 修改配置文件2.5 重新测试和结果 0 引言 grid map学习笔记1已…

Go学习第六天

Golang变量内置pair结构详细说明 变量包括&#xff08;type, value&#xff09;两部分type 包括 static type和concrete type. 简单来说 static type是你在编码是看见的类型(如int、string)&#xff0c;concrete type是runtime系统看见的类型类型断言能否成功&#xff0c;取决…

electron+vue3全家桶+vite项目搭建【25】使用electron-updater自动更新应用

文章目录 引入实现效果实现步骤引入依赖配置electron-buidler文件封装版本升级工具类主进程调用版本更新校验渲染进程封装方法调用 测试版本更新 引入 demo项目地址 electron-updater官网 我们不可能每次发布新的版本都让用户去手动下载安装最新的包&#xff0c;而是应用可以…

vue2-组件和插件的区别

1、组件是什么&#xff1f; 组件就是把图形、非图形的各种逻辑均抽象为一个统一的概念&#xff08;组件&#xff09;来实现开发的模式&#xff0c;在vue中每一个.vue文件都可以被视为一个组件。 组件的优势&#xff1a; 降低整个系统的耦合度&#xff0c;在保持接口不变的情况下…

Qt QThread的moveToThread方法使用

Qt线程简介 从 Qt4.4 版本之后&#xff0c;因为 QThread 的 run 方法创建新线程这样实现与 Qt 设计的理念不符&#xff0c;Qt 主推使用 moveToThread 方法来创建新线程。QThread 应该被看做是操作系统线程的接口或控制点&#xff0c;而不应该包含需要在新线程中运行的代码。需…

kodi 电视遥控器 不起作用 ,无法唤醒视频OSD

最近电视盒子上安装了kodi播放器&#xff0c;但是安装好之后&#xff0c;盒子本身的遥控器就不起作用了&#xff0c;之前看网络上其他的文章&#xff0c;需要重新安装tv 控制器&#xff0c;重新映射&#xff0c;比较麻烦&#xff0c;而且观看视频的时候没办法唤起OSD切换字幕和…

在美国,信用分数超过800,这是一个很好的分数吗?

超过800的信用评分被认为是极好的&#xff0c;而且这确实是可以实现的。事实上&#xff0c;美国有很多人的信用评分都在这个范围内。 信用评分是一个数字化的表示&#xff0c;反映了一个人的信用值得信赖度&#xff0c;贷款机构用它来评估这个人偿还债务的可能性。最广泛使用的…

PyCharm安装使用2023年教程,PyCharm与现流行所有编辑器对比。

与PyCharm类似的功能和特性的集成开发环境&#xff08;IDE&#xff09;和代码编辑器有以下几种&#xff1a; Visual Studio Code&#xff08;VS Code&#xff09;&#xff1a;由Microsoft开发&#xff0c;VS Code是一个高度可定制和可扩展的代码编辑器。它支持多种编程语言&am…

为什么list.sort()比Stream().sorted()更快?

真的更好吗&#xff1f; 先简单写个demo List<Integer> userList new ArrayList<>();Random rand new Random();for (int i 0; i < 10000 ; i) {userList.add(rand.nextInt(1000));}List<Integer> userList2 new ArrayList<>();userList2.add…

ORA-48913: Writing into trace file failed, file size limit [50000000] reached

检查某环境的alert_orcl1.log时&#xff0c;发现有很多的ORA-48913报错&#xff0c;细节如下 Sat Jul 22 19:34:04 2023 Non critical error ORA-48913 caught while writing to trace file "/u01/app/oracle/diag/rdbms/orcl/orcl1/trace/orcl1_dw00_138010.trc" E…

LeetCode 热题 100 JavaScript--108. 将有序数组转换为二叉搜索树

给你一个整数数组 nums &#xff0c;其中元素已经按 升序 排列&#xff0c;请你将其转换为一棵 高度平衡 二叉搜索树。 高度平衡 二叉树是一棵满足「每个节点的左右两个子树的高度差的绝对值不超过 1 」的二叉树。 提示&#xff1a; 1 < nums.length < 104 -104 < n…

C#利用自定义特性以及反射,来提大型项目的开发的效率

在大型项目的开发过程中&#xff0c;需要多人协同工作&#xff0c;来加速项目完成进度。 比如一个软件有100个form&#xff0c;分给100个人来写&#xff0c;每个人完成自己的Form.cs的编写之后&#xff0c;要在Mainform调用自己写的Form。 如果按照正常的Form form1 new For…

摄像头电池组和平衡车电池组

摄像头电池组 Wh~是电量 Wh V*Ah 毫安(mA)~是电流 电量是9.62Wh&#xff0c;电压是 3.7v 9.62 wh / 3.7v 2.6 Ah 2600mAH 4个并联电池&#xff1a;10400mAH / 4 2600mAH PH2.0mm-2Pins 平衡车 72 wh / 36v 2 Ah 2000mAH 对比自己买的单粒电池 vs 摄像头和平衡车的 …

云安全攻防(四)之 云原生技术

云原生技术 容器技术 容器与虚拟化 虚拟化&#xff08;Virtualization&#xff09;和容器&#xff08;Container&#xff09;都是系统虚拟化的实现技术&#xff0c;可实现系统资源的”一虚多“共享。容器技术可以理解成一种”轻量的虚拟化“方式&#xff0c;此处的”轻量“主…

JNI之Java实现远程打印

打印机是最常见的办公设备了。一般情况下如果需要实现打印&#xff0c;可通过前端print.js包来完成。但是&#xff0c;如果要实现智能办公打印&#xff0c;就可以使用JNI技术、封装接口、远程调用实现完成。 导包 jacob&#xff1a;Java COM Bridge <dependency><g…

vim粘贴内容格式混乱解决方法

问题 复制本地文件内容后&#xff0c;咱贴到vim文本内&#xff0c;格式错乱 解决方法 打开vim配置文件 最后面加入一行 vim /etc/vimrc set pastetoggle<F11> 开发vim文件&#xff0c;进入后先按F11进入交互模式 shift insert 再次粘贴 解决

原型模式(C++)

定义 使用原型实例指定创建对象的种类&#xff0c;然后通过拷贝这些原型来创建新的对象。 应用场景 在软件系统中&#xff0c;经常面临着“某些结构复杂的对象”的创建工作;由于需求的变化&#xff0c;这些对象经常面临着剧烈的变化&#xff0c;但是它们却拥有比较稳定一致的…

SpringCloud Gateway获取请求响应body大小

前提 本文获取请求、响应body大小方法的前提 : 网关只做转发逻辑&#xff0c;不修改请求、相应的body内容。 SpringCloud Gateway内部的机制类似下图&#xff0c;HttpServer&#xff08;也就是NettyServer&#xff09;接收外部的请求&#xff0c;在Gateway内部请求将会通过Htt…

外部排序算法总结

一.内排总结 在之前博客里&#xff0c;博主已经介绍了各种内部排序算法的原理和C语言代码实现&#xff0c;不懂的朋友可以在同系列专栏里选择查看&#xff0c;今天介绍常见排序算法的最后一点&#xff0c;也就是外部排序。在此之前&#xff0c;我们先对外部排序的各种算法做一…