我在获取和设置联系人的图像作为视图的背景时遇到了问题,令人惊讶的是,关于如何执行此操作的示例很少.我正在尝试构建类似于显示大型联系人照片的人物应用程序.
这就是我现在正在做的事情:
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.valueOf(id));
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(context.getContentResolver(), uri);
Bitmap bm = BitmapFactory.decodeStream(input);
Drawable d = new BitmapDrawable(bm);
button.setBackgroundDrawable(drawable);
Run Code Online (Sandbox Code Playgroud)
这适用于它使用的URI获取缩略图,因此即使有大照片,当缩放以适合imageView时,图像看起来非常糟糕.我知道另一种方法来获取实际获得大照片的URI:
final Uri imageUri = Uri.parse(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.PHOTO_URI)));
Run Code Online (Sandbox Code Playgroud)
但是我没有设法将它带到imageView,也许上面的代码可以适应使用第二个uri.如果您知道如何使用第二个uri,或者如果有更简单的方法来获取联系人图像而不是通过URI,请告诉我.任何信息都将被感谢.
在获取URI方面做得很好.你快到了.首先考虑使用PHOTO_THUMBNAIL_URI而不是PHOTO_URI,因为它可能是您在尺寸方面所需要的.
编辑:FYI,PHOTO_THUMBNAIL_URI从API 11开始可用.您仍然可以有条件地使用它.
如果你想使用一个外部库,' Android通用图像加载器 '绝对是你想要的,从几天前它的1.7.1版本开始,它增加了对内容方案的支持,它非常聪明,内存明智的.它还有很多自定义选项.
编辑:这个lib已经死了.请改用Fresco.
如果你更喜欢你的最终包大小并自己编写代码,
您需要获取并解码该内容的输入流; 这应该在后台线程上完成.看看这个connivence方法; 您使用图像视图和您获得的uri初始化它,并在您要加载ImageView时启动它.
private class ContactThumbnailTask extends AsyncTask<Void, Void, Bitmap> {
private WeakReference<ImageView> imageViewWeakReference;
private Uri uri;
private String path;
private Context context;
public ContactThumbnailTask(ImageView imageView, Uri uri, Context context) {
this.uri = uri;
this.imageViewWeakReference = new WeakReference<ImageView>(imageView);
this.path = (String)imageViewWeakReference.get().getTag(); // to make sure we don't put the wrong image on callback
this.context = context;
}
@Override
protected Bitmap doInBackground(Void... params) {
InputStream is = null;
try {
is = context.getContentResolver().openInputStream(uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap image = null;
if (null!= is)
image= BitmapFactory.decodeStream(is);
return image;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (imageViewWeakReference != null && imageViewWeakReference.get() != null && ((String)imageViewWeakReference.get().getTag()).equals(path) && null != bitmap)
imageViewWeakReference.get().setImageBitmap(bitmap);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4647 次 |
最近记录: |