首页 > 解决方案 > 如何在颤动中使用 BoxFit.contain 圆角图像

问题描述

我的问题是,当我使用具有特定大小的容器包装图像并使用 BoxFit.contain 属性时,它不会对图像进行四舍五入。查看下图: 我认为该图像不能自圆,因为它不能扩展以填充容器。我知道我可以使用 BoxFit.cover,但我想使用 BoxFit.contain,因为我的空间和图像可以是任意大小。我的代码:图片链接

@override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey,
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Container(
          color: Colors.red,
          height: 300,
          width: 300,
          child: ClipRRect(
            borderRadius: BorderRadius.circular(16),
            child: Image.network(
              'https://i.ytimg.com/vi/fq4N0hgOWzU/maxresdefault.jpg',
              fit: BoxFit.contain,
            ),
          ),
        ),
      ),

    );
  }

标签: imageflutterflutter-layout

解决方案


你必须ClipRRectCenter或任何小部件包装你的小Align部件。

如果父级未指定任何对齐属性,大多数小部件将尝试填充其父级。

在您的情况下,ClipRRect填充了其父Container级(300x300),因为容器未指定与其子级的任何对齐方式。并且具有contain属性的图像将尝试保持图像比例并在ClipRRect小部件中居中。所以它使ClipRRect角落不可见或没有效果。

演示: 飞镖板

Scaffold(
  backgroundColor: Colors.grey,
  appBar: AppBar(
    title: Text("My image size"),
  ),
  body: Center(
    child: Container(
      color: Colors.red,
      height: 300,
      width: 300,
      child: Center(
        child: ClipRRect(
          borderRadius: BorderRadius.circular(16),
          child: Image.network(
            'https://mfiles.alphacoders.com/847/847991.jpg',
            fit: BoxFit.contain,
          ),
        ),
      ),
    ),
  ),
)

编辑:在这里我使用Center了小部件。但是您也可以在Container小部件中简单地指定对齐属性。


推荐阅读