Flutter Widget : centerSlice 属性

写在前面

在 Flutter 的项目中,有时会用到 Android 上的一个叫点9图的东西。点9图是一种可以让我们在设定的某个方向上,对图片的某部分进行拉伸。

就我目前所知,Flutter 上对点9图的支持跟 Android 上的有一些区别。Flutter 是在我们确定点9图的中心区域后,它会自动去拉伸水平方向和竖直方向。似乎如果图片是比较规范的图形的话,普通图片也是可以。

内容

在 Flutter 上,图片相关的控件会有一个叫centerSlice的属性,用来帮我们处理点9图。

 /// The center slice for a nine-patch image.
  ///
  /// The region of the image inside the center slice will be stretched both
  /// horizontally and vertically to fit the image into its destination. The
  /// region of the image above and below the center slice will be stretched
  /// only horizontally and the region of the image to the left and right of
  /// the center slice will be stretched only vertically.
  ///
  /// The stretching will be applied in order to make the image fit into the box
  /// specified by [fit]. When [centerSlice] is not null, [fit] defaults to
  /// [BoxFit.fill], which distorts the destination image size relative to the
  /// image's original aspect ratio. Values of [BoxFit] which do not distort the
  /// destination image size will result in [centerSlice] having no effect
  /// (since the nine regions of the image will be rendered with the same
  /// scaling, as if it wasn't specified).
  final Rect? centerSlice;

centerSliceRect类型,因此它就是一个矩形。

以这张图为例,它的尺寸是 50 * 50。
请添加图片描述
在使用的时候,我们先确定它的中间矩形,也就是centerSlice,然后它就会沿着这矩形的四条边进行延伸,把图片分割成 9 个部分:
请添加图片描述
然后我们取它的中心矩形的位置:

Rect.fromLTRB(15, 15, 35, 35)

这里Rect.fromLTRB(15, 15, 35, 35)就是中间的矩形。

假设我们运行以下的代码

    Image.asset(
            'assets/black_square.png',
            height: 100,
            width: 350,
            centerSlice: Rect.fromLTRB(15, 15, 35, 35),
          )

那么实际的效果就是在这9个部分里,以centerSlice为中心部分,四个角的矩形部分不会改变,而左右上下四部分就会进行拉伸。这样在我们这个例子的图里,就不会因为拉伸导致圆角变形。

Column(
        children: [
          Container(
            height: 100,
            width: 330,
            color: Colors.red,
          ),
          Image.asset(
            'assets/black_square.png',
            height: 100,
            width: 330,
            centerSlice: Rect.fromLTRB(15, 15, 35, 35),
          ),
          Image.asset(
            'assets/black_square.png',
            height: 100,
            width: 330,
            fit: BoxFit.fill,
          ),
          Image.asset(
            'assets/black_square.png',
            height: 100,
            width: 330,
            fit: BoxFit.fitWidth,
          )
        ],
      )

请添加图片描述

参考

How to display .9.png format of a picture in flutter?
Flutter centerSlice .9图的理解

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值