獲取View的截圖-將View轉換為Bitmap對象


開發中,有時候需要獲取View的截圖來做動畫來達到動畫流程的目的

原理:將View的內容畫到一個Bitmap畫布上,然后取出

下面封裝了一個從View生成Bitmap的工具類

/** * 將View轉換為Bitmap對象 */
public class ViewToBitmapUtil { private static final String TAG = "ViewToBitmapUtil"; public static Bitmap convertViewToBitmap(View view) { view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 
            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); view.buildDrawingCache(); Bitmap bitmap = view.getDrawingCache();
     // 或者可以使用下面的方法
     // view.setDrawingCacheEnabled(true);
     // Bitmap bmp = Bitmap.createBitmap(view.getDrawingCache());

 

     return bitmap; } public static Bitmap convertViewToBitmap(View view, int bitmapWidth, int bitmapHeight) { Bitmap bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888); view.draw(new Canvas(bitmap)); return bitmap; } public static void getScreenRectOfView(View view, Rect outRect) { int pos[] = new int[2]; view.getLocationOnScreen(pos); outRect.set(pos[0], pos[1], pos[0] + view.getWidth(), pos[1] + view.getHeight()); }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM