一、基本介绍
图片组件是显示图像的组件,Image 组件有很多构造函数
构造函数 | 说明 |
---|---|
Image.asset(...) | 本地资源 |
Image.file(…) | 文件 |
Image.network(…) | 远程 |
Image.memory(…) | Uint8List bytes 格式 |
常用属性
名称 | 类型 | 说明 |
---|---|---|
alignment | Alignment | 对齐方式 |
colorcolorBlendMode | 设置图片的背景颜色,通常和 colorBlendMode 配合一起使用,这样可以是图片颜色和背景色混合。 | |
fit | BoxFit | fit 属性用来控制图片的拉伸和挤压,这都是根据父容器来的。 BoxFit.fill:全图显示,图片会被拉伸,并充满父容器。 BoxFit.contain:全图显示,显示原比例,可能会有空隙。 BoxFit.cover:显示可能拉伸,可能裁切,充满(图片要充满整个容器,还不变形)。 BoxFit.fitWidth:宽度充满(横向充满),显示可能拉伸,可能裁切。 BoxFit.fitHeight :高度充满(竖向充满),显示可能拉伸,可能裁切。 BoxFit.scaleDown:效果和 contain 差不多,但是此属性不允许显示超过源图片大小,可小不可大 |
repeat | 平铺 ImageRepeat.repeat:横向和纵向都进行重复,直到铺满整个画布。 ImageRepeat.repeatX::横向重复,纵向不重复。 ImageRepeat.repeatY:纵向重复,横向不重复。 |
|
width | 宽度 一般结合 ClipOval 才能看到效果 |
|
height | 高度 一般结合 ClipOval 才能看到效果 |
更多属性参考:https://api.flutter.dev/flutter/widgets/Image-class.html
二、引入本地图片
- 添加图片资源
图片资源目录
- 修改 pubspec.yaml
1 2 3 4 5 | uses-material-design: true assets: - imgs/01.jpeg - imgs/2.0x/01.jpeg - imgs/3.0x/01.jpeg |
- 代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | // 本地图片 组件 class AssetImage extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: Container( child: Image.asset("imgs/01.jpeg"), width: 200, height: 200, decoration: BoxDecoration( color: Colors.yellow ), ) ); } } |
三、引入远程图片
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | // 远程图片 组件 class networkImage extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: Container( child: Image.network( "https://pic.rmb.bdstatic.com/c86255e8028696139d3e3e4bb44c047b.png", alignment: Alignment.bottomRight, // color: Colors.blue, // colorBlendMode: BlendMode.screen, // fit: BoxFit.cover, repeat: ImageRepeat.repeat, ), width: 300, height: 800, decoration: BoxDecoration( color: Colors.yellow ), // color: Colors.red, ) ); } } |
四、实现圆角效果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | // 圆角图片 组件 class BorderRadiusImage extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: Container( width: 300, height: 300, decoration: BoxDecoration( color: Colors.yellow, // borderRadius: BorderRadius.all( // Radius.circular(30) // ), borderRadius: BorderRadius.circular(20), image: DecorationImage( image: NetworkImage("https://pic.rmb.bdstatic.com/c86255e8028696139d3e3e4bb44c047b.png") ) ), ) ); } } |
五、实现圆形效果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | // 圆形图片 组件 class ClipOvalImage extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: Container( color: Colors.yellow, child: ClipOval( child: Image.asset("imgs/02.jpeg", width: 200, height: 200, fit: BoxFit.cover ) ) ) ); } } |