2013-01-06 56 views
1

我试图用封闭样本的Chris Banes的PhotoView库。我对样本进行了一些更改以从URL(在Internet上)加载图像,而不是从可绘制的样本加载。这里是代码:如何在PhotoView中加载URL图像

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

尝试将图像加载到位图中,然后将位图设置为imageview。

网址为位图:

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()

+0

嗨,谢谢你的建议。但是,它只是从setimageDrawable切换到setimagebitmap。问题仍然存在。或者我不明白你的要点,如果有的话请更多地解释我。谢谢 –

-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();