2013-01-06 94 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();