Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> Android View轉化Bitmap

Android View轉化Bitmap

編輯:關於android開發

Android View轉化Bitmap


在View類中的onDraw方法的參數Canvas是View繪制的背景,要將View轉換為Bitmap實際上就是讓Canvas上的繪制操作繪制到Bitmap上。      View轉化為Bitmap也稱為截屏,讓用戶看到的View視圖轉化為圖片的過程。      關於View轉化Bitmap涉及到的View類中的方法有:    
   protected void onDraw(Canvas canvas)
   public void buildDrawingCache()
   public void destroyDrawingCache()
   public Bitmap getDrawingCache()
   public void setDrawingCacheEnabled(boolean enabled)

 

       下面是常見的幾個View截屏的示例:    1.View轉Bitmap  
public final Bitmap screenShot(View view) {
        if (null == view) {
            throw new IllegalArgumentException("parameter can't be null.");
        }
        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bitmap = view.getDrawingCache();
        return bitmap;
    }
  

 

  2. Activity轉Bitmap,不帶狀態欄    
public final Bitmap screenShot(Activity activity) {
        if (null == activity) {
            throw new IllegalArgumentException("parameter can't be null.");
        }
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();

        Bitmap b1 = view.getDrawingCache();
        Rect frame = new Rect();
        view.getWindowVisibleDisplayFrame(frame);

        int statusBarHeight = frame.top;

        Point point = new Point();
        activity.getWindowManager().getDefaultDisplay().getSize(point);

        int width = point.x;
        int height = point.y;

        Bitmap b2 = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight);
        view.destroyDrawingCache();
        return b2;
    }

 

  3. ScrollView轉長Bitmap(類似錘子便簽的截長圖)    
 public final Bitmap screenShot(ScrollView scrollView) {
        if (null == scrollView) {
            throw new IllegalArgumentException("parameter can't be null.");
        }
        int height = 0;
        Bitmap bitmap;
        for (int i = 0, s = scrollView.getChildCount(); i < s; i++) {
            height += scrollView.getChildAt(i).getHeight();
            scrollView.getChildAt(i).setBackgroundResource(android.R.drawable.screen_background_light);
        }
        bitmap = Bitmap.createBitmap(scrollView.getWidth(), height, Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(bitmap);
        scrollView.draw(canvas);
        return bitmap;
    }

 

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved