2013-04-11 58 views
0

我試圖製作一個簡單的圖片庫,通過它我可以設置壁紙;我正在使用下面的代碼從下載文件夾中獲取文件並將其顯示在滾動視圖中。從horizo​​ntol滾動條獲取當前圖像android

我能夠做到這一點,但現在我想獲取當前顯示的圖像,以便我可以將該圖像設置爲壁紙。

下面是我對我的活動類的代碼:

public class MainActivity extends Activity { 

LinearLayout myGallery; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     myGallery = (LinearLayout)findViewById(R.id.mygallery); 

     String ExternalStorageDirectoryPath = Environment 
      .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) 
      .getAbsolutePath(); 

     String targetPath = ExternalStorageDirectoryPath ; 

     Toast.makeText(getApplicationContext(), targetPath, Toast.LENGTH_LONG).show(); 
     File targetDirector = new File(targetPath); 

     File[] files = targetDirector.listFiles(); 
     for (File file : files){ 
     myGallery.addView(insertPhoto(file.getAbsolutePath())); 

     }  
    } 

    View insertPhoto(String path){ 
    Bitmap bm = decodeSampledBitmapFromUri(path, 520, 520); 

    LinearLayout layout = new LinearLayout(getApplicationContext()); 
    layout.setLayoutParams(new LayoutParams(550, 550));//Size of view 
    layout.setGravity(Gravity.CENTER); 

    ImageView imageView = new ImageView(getApplicationContext()); 
    imageView.setLayoutParams(new LayoutParams(520, 520)); 
    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); 
    imageView.setImageBitmap(bm); 

    layout.addView(imageView); 
    return layout; 
    } 

    public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight) { 
    Bitmap bm = null; 

    // First decode with inJustDecodeBounds=true to check dimensions 
    final BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inJustDecodeBounds = true; 
    BitmapFactory.decodeFile(path, options); 

    // Calculate inSampleSize 
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 

    // Decode bitmap with inSampleSize set 
    options.inJustDecodeBounds = false; 
    bm = BitmapFactory.decodeFile(path, options); 

    return bm; 
    } 

    public int calculateInSampleSize(

    BitmapFactory.Options options, int reqWidth, int reqHeight) { 
    // Raw height and width of image 
    final int height = options.outHeight; 
    final int width = options.outWidth; 
    int inSampleSize = 1; 

    if (height > reqHeight || width > reqWidth) { 
     if (width > height) { 
     inSampleSize = Math.round((float)height/(float)reqHeight); 
     } else { 
     inSampleSize = Math.round((float)width/(float)reqWidth); 
     } 
    } 

    return inSampleSize; 
    } 

} 

請告訴我如何可以獲取當前顯示在滾動視圖中的圖像。

感謝 阿曼

+0

對此有何幫助...? – 2013-04-12 01:28:34

回答

0

其被5個月還沒有回答,但我想我會盡量回答。 我認爲你需要一個自定義的視圖即。與畫布。創建一個畫布,然後在畫布中創建一個位圖。之後,當你以URI的形式從線性佈局獲得一個位圖時,在你的代碼中使用一個方法decodeSampledBitmapFromUri獲得一個位圖,只需將位圖分配給畫布上創建的位圖即可。

相關問題