Android 获得View截屏最优方案


Android 获得View截屏最优方案

/**
 * 获得View的截屏 Bitmap
 *
 * @param view
 * @return
 */
public static Bitmap getMagicDrawingCache(Context context,View view,boolean quick_cache) {
     
    Bitmap bitmap = (Bitmap) view.getTag(R.id.cacheBitmapKey);
    Boolean dirty = (Boolean) view.getTag(R.id.cacheBitmapDirtyKey);
    if (view.getWidth() + view.getHeight() == 0) {
     
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
    }
    int viewWidth = view.getWidth();
    int viewHeight = view.getHeight();
    if (bitmap == null || bitmap.getWidth() != viewWidth || bitmap.getHeight() != viewHeight) {
     
        if (bitmap != null && !bitmap.isRecycled()) {
     
            bitmap.recycle();
        }
        bitmap = Bitmap.createBitmap(viewWidth, viewHeight, Bitmap.Config.ARGB_8888);
        view.setTag(R.id.cacheBitmapKey, bitmap);
        dirty = true;
    }
    if (dirty == true || !quick_cache) {
     
        bitmap.eraseColor(context.getResources().getColor(android.R.color.transparent));
        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);
        view.setTag(R.id.cacheBitmapDirtyKey, false);
    }
    return bitmap;
}

xml资源需要添加id

	<item type="id" name="cacheBitmapKey"/>
    <item type="id" name="cacheBitmapDirtyKey"/>

你可能感兴趣的:(Android)