我正在尝试使用Chris Banes的PhotoView库来附上样本。我对示例进行了一些更改,以便从URL(在Internet上)加载图像,而不是从drawable作为示例加载图像。这是代码:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = (ImageView) findViewById(R.id.iv_photo);
mCurrMatrixTv = (TextView) findViewById(R.id.tv_current_matrix);
//here's the method to load URL image from URL
new LoadImage().execute();
mAttacher = new PhotoViewAttacher(mImageView);
}
private class LoadImage extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
// Simulates a background job.
try {
mImageView.setImageDrawable(grabImageFromUrl(image_url));
} catch (Exception e) {
e.getStackTrace().toString();
}
return null;
}
}
private Drawable grabImageFromUrl(String url) throws Exception {
return Drawable.createFromStream((InputStream)new URL(url).getContent(), "src");
}
问题是图像未加载,只返回空白页面。当我尝试一些捏拉缩放操作,图像被加载并正常工作时,发生了奇怪的事情。有人有建议吗?感谢。
答案 0 :(得分:0)
首先尝试将图像加载到位图中,然后将位图设置为图像视图。
Url to bitmap:
public static Bitmap getBitmapFromURL(String src) { try { URL url = new URL(src); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); Bitmap myBitmap = BitmapFactory.decodeStream(input); return myBitmap; } catch (IOException e) { e.printStackTrace(); return null; } }
然后使用iv.setimagebitmap()
答案 1 :(得分:-1)
private Bitmap bmp;
bmp = new Bitmap[1];
// to fetch the image
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = calculateInSampleSize(options, screenWidth, screenHeight);
options.inJustDecodeBounds = false;
final Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(url, new Rect(), options);
// to set the image
Runnable action = new Runnable() {
public void run() { bmp = bitmap
}
};
runOnUiThread(action);
现在你有了bmp中的图像。拿起它并设置适合您的图库的适配器。
ImageView imageView = new ImageView(container.getContext());
PhotoViewAttacher attacher = new PhotoViewAttacher(imageView);
imageView.setImageBitmap(bmp);
attacher.update();