美文网首页
2019-09-28 从View获取Bitmap

2019-09-28 从View获取Bitmap

作者: 兣甅 | 来源:发表于2019-09-28 22:14 被阅读0次
public class ViewUtil {

  /**
   * 测量这个view,最后通过getMeasuredWidth()、getMeasuredHeight()获取宽度和高度
   *
   * @param v 需要测量的View
   */
  public static void measureView(View v) {
    if (v == null) {
      return;
    }
    ViewGroup.LayoutParams p = v.getLayoutParams();
    if (p == null) {
      p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
          ViewGroup.LayoutParams.WRAP_CONTENT);
    }
    int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
    int lpHeight = p.height;
    int childHeightSpec;
    if (lpHeight > 0) {
      childHeightSpec = View.MeasureSpec.makeMeasureSpec(lpHeight,
          View.MeasureSpec.EXACTLY);
    } else {
      childHeightSpec = View.MeasureSpec.makeMeasureSpec(0,
          View.MeasureSpec.UNSPECIFIED);
    }
    v.measure(childWidthSpec, childHeightSpec);
  }

  /**
   * 测量view宽度
   *
   * @param view 需要测量的View
   *
   * @return View的宽度
   */
  public static int measureVieWidth(View view) {
    if (view == null) {
      return 0;
    }
    int width = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
    int height = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
    view.measure(width, height);
    return view.getMeasuredWidth();
  }

  /**
   * 测量view高度
   *
   * @param view 需要测量的View
   *
   * @return View的高度
   */
  public static int measureViewHeight(View view) {
    if (view == null) {
      return 0;
    }
    int width = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
    int height = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
    view.measure(width, height);
    return view.getMeasuredHeight();
  }

  /**
   * 通过drawingCache获取bitmap
   */
  public static Bitmap convertViewToBitmap2(View view) {
    view.setDrawingCacheEnabled(true);
    Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
    //如果不调用这个方法,每次生成的bitmap相同
    view.setDrawingCacheEnabled(false);
    return bitmap;
  }

  /**
   * 通过canvas复制view的bitmap
   */
  public static Bitmap copyByCanvas2(View view) {
    int width = view.getMeasuredWidth();
    int height = view.getMeasuredHeight();
    Bitmap bp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bp);
    view.draw(canvas);
    canvas.save();
    return bp;
  }
}

相关文章

网友评论

      本文标题:2019-09-28 从View获取Bitmap

      本文链接:https://www.haomeiwen.com/subject/ehcxpctx.html