- 原文链接: Advanced Loading
- 原文作者: Future Studio
- 译文出自: 小鄧子的简书
- 译者: 小鄧子
- 状态: 完成
从Resources中加载
首先,从Android的资源文件中加载。你需要提供一个int
类型的资源ID,而不是一个String
类型的字符串指向网络URL。
int resourceId = R.mipmap.ic_launcher;
Picasso
.with(context)
.load(resourceId)
.into(imageViewResource);
不必对R.mipmap的感到困惑,它只不过是处理Android图标的新方案。
从File中加载
第二就是从文件中加载。这对于允许用户通过照片选择来显示图像来说是非常重要的(类似于Gallery)。传入的参数仅仅是一个File
对象。示例如下:
// this file probably does not exist on your device. However, you can use any file path, which points to an image file
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Running.jpg");
Picasso
.with(context)
.load(file)
.into(imageViewFile);
从Uri地址加载
最后,你也可以通过一个可用的Uri
来加载图像。这与之前的加载方式没有什么不同。
// this could be any Uri. for demonstration purposes we're just creating an Uri pointing to a launcher icon
Uri uri = resourceIdToUri(context, R.mipmap.future_studio_launcher);
Picasso
.with(context)
.load(uri)
.into(imageViewUri);
resourceIdToUri()
只是一个将resourceId转换成Uri
的简单函数。
public static final String ANDROID_RESOURCE = "android.resource://";
public static final String FOREWARD_SLASH = "/";
private static Uri resourceIdToUri(Context context, int resourceId) {
return Uri.parse(ANDROID_RESOURCE + context.getPackageName() + FOREWARD_SLASH + resourceId);
}
然而,值得一提的是,这个Uri
,不一定非要通过resourceId来生成,它可以是任意的Uri
。