2015-06-18 62 views
-2

當我從一個視圖的DrawingCache中獲取位圖時,我得不到任何錯誤,但是我沒有看到有效的位圖。我究竟做錯了什麼?從視圖生成位圖

我用它來生成位圖的代碼:

SharePhotoView sharePhotoView = SharePhotoView_.build(this); 
sharePhotoView.bind(mCatch); 

sharePhotoView.setDrawingCacheEnabled(true); 
sharePhotoView.buildDrawingCache(); 
Bitmap bitmap = sharePhotoView.getDrawingCache(); 

catchImage.setImageBitmap(bitmap); 

我用它來使視圖代碼:

@EViewGroup(R.layout.share_photo) 
public class SharePhotoView extends LinearLayout{ 

    @ViewById 
    ImageView catchImage; 

    public SharePhotoView(Context context) { 
     super(context); 
    } 

    public void bind(Catch catchItem) { 
     Bitmap bitmap = BitmapFactory.decodeFile(catchItem.getImage().getPath()); 

     catchImage.setImageBitmap(bitmap); 

    } 
} 

回答

0

發現了一個方法:

public static Bitmap getScreenViewBitmap(View v) { 
    v.setDrawingCacheEnabled(true); 

    // this is the important code :) 
    // Without it the view will have a dimension of 0,0 and the bitmap will be null 
    v.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), 
      View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); 
    v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight()); 

    v.buildDrawingCache(true); 
    Bitmap b = Bitmap.createBitmap(v.getDrawingCache()); 
    v.setDrawingCacheEnabled(false); // clear drawing cache 

    return b; 
} 

來源:http://www.jattcode.com/getting-bitmap-from-a-view-visible-invisible-oncreate/

0

使用此代碼爲位圖,從圖:

Bitmap bitmap; 
      try { 
       bitmap = Bitmap.createBitmap(YOUR_VIEW.getWidth(), YOUR_VIEW.getHeight(), 
         Bitmap.Config.ARGB_8888); 

       Canvas canvas = new Canvas(bitmap); 
       YOUR_VIEW.draw(canvas); 

       File root = Environment.getExternalStoragePublicDirectory(Environment.PICTURES); 

       String fname = "NAME_OF_FILE.jpg"; 
       file = new File(root, fname); 

       try { 
        if (!root.exists()) { 
        root.mkdir(); 
       } 
        FileOutputStream out = new FileOutputStream(file); 
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); 
        out.flush(); 
        out.close(); 
        YOUR_VIEW.destroyDrawingCache(); 

       } catch (Exception e) { 
        e.printStackTrace(); 
       } 

      } catch (Exception e) { 
      } 
+0

這是行不通的。 –

+0

我更新了創建文件夾的答案(如果不存在) – Santiago

+0

沒有保存它是不可能的? –