目录
介绍
Flutter框架对加载过的图片是有缓存的(内存),默认最大缓存数量是1000,最大缓存空间为100M
关于Flutter图片的加载有多种形式
方法 释义 Image() 从ImageProvider中获取图片,从本质上看,下面的几个方法都是他的具体实现。 Image.asset(String name) 从AssetBundler中获取图片 Image.network(String src) 显示网络图片 Image.file(File file) 从File中获取图片 Image.memory(Uint8List bytes) 从Uint8List中显示图片
Image-Fit属性
我们先来看一段代码
class HomeText extends StatelessWidget{ @override Widget build(BuildContext context) { return Container( margin: EdgeInsets.all(20), width: 300, height: 300, color: Colors.yellow, child: Image.network( 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1591173779064&di=c155ead722524ac488fa65833e4c8cc8&imgtype=0&src=http%3A%2F%2Fimg.mp.itc.cn%2Fupload%2F20161127%2F36b8d95b15ce4f7baa3d938553c850fb_th.jpeg', fit: BoxFit.fill, ), ); } }
运行效果
fit设置不同属性图片显示对比
BoxFit.contain 显示整张图片,按照原始比例缩放显示 ![]()
BoxFit.fill 显示整张图片,拉伸填充全部可显示区域 ![]()
BoxFit.cover 按照原始比例缩放,可能裁剪,填满可显示区域 ![]()
BoxFit.fitHeight 按照原始比例缩放,可能裁剪,高度优先填满 ![]()
BoxFit.fitWidth 按照原始比例缩放,可能裁剪宽度优先填满 ![]()
BoxFit.none 图片居中显示,不缩放原图,可能被裁剪 ![]()
BoxFit.scaleDown 显示整张图片,只能缩小或者原图显示 ![]()
常用属性
color: Colors.blue,
colorBlendMode: BlendMode.saturation,
这两个属性要在一起使用,就是颜色和图片混合
BlendMode属性实在是太多了,这里就举一个例子
repeat: ImageRepeat.repeat 设置图片填充方式,当图片本身大小小于显示空间时,指定图片的重复规则
centerSlice属性
centerSlice: Rect.fromLTWH(10, 10, 10, 10)
设置图片内部拉伸,相当于在图片内部设置了一个.9图,但是需要注意的是,要在显示图片的大小
大于原图的情况下才可以使用这个属性,要不然会报错
结合Container使用Image
Image.network
class HomeText extends StatelessWidget { @override Widget build(BuildContext context) { return Container( margin: EdgeInsets.all(20), width: 300, height: 300, color: Colors.yellow, child: Image.network( 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1591175847643&di=6e41a32b6e6355aacbfae14d03439a83&imgtype=0&src=http%3A%2F%2Fimgwx4.2345.com%2Fdypcimg%2Fdongman%2Fimg%2F2%2F25%2Fsup75205_223x310.jpg', fit: BoxFit.contain, color: Colors.blue, colorBlendMode: BlendMode.saturation, ), ); } }
Image.asset
- 在根目录下新建images文件夹。由于Flutter加载图片时需要2倍图、3倍图,默认图。所以需要同时新建2.0x和3.0x文件夹。(iOS中常有这种)
首先创建文
![]()
然后打开pubspec.yaml,按它的要求写,注意 - image,中间的空格一定不要忘
然后
child: Image.asset( 'images/weixin_invite.png', fit: BoxFit.contain, color: Colors.blue, colorBlendMode: BlendMode.saturation, ),
执行结果
Image.file
我的相册有一张图片,复制图片地址
然后在manifest文件中添加读写权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
child: Image.file( File('/storage/emulated/0/Download/hkd.png'), fit: BoxFit.contain, color: Colors.blue, colorBlendMode: BlendMode.saturation, ),
运行结果啥也没显示,不知道哪里错了
Image.memory
用来将一个
byte
数组加载成图片,用法如下:new Image.memory(bytes)