欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android 将view 转换为Bitmap出现空指针问题解决办法

程序员文章站 2023-11-24 21:42:04
android 将view 转换为bitmap出现空指针问题解决办法 在做android 项目的时候,有时候可能有这样的需求,将一个view 或者一个布局文件转换成一个b...

android 将view 转换为bitmap出现空指针问题解决办法

在做android 项目的时候,有时候可能有这样的需求,将一个view 或者一个布局文件转换成一个bitmap  对象。

方法其实大都差不多。但这其中有一些小细节需要注意一下。最近在项目中用到了这个功能,现在分享一下,希望能帮助到遇到果这个

问题的人。

 首先是转换 的代码:

/**
   * 将view(布局) 转换为bitmap
   * @param view
   * @return
   */
  public static bitmap createbitmap(view view){
    view.setdrawingcacheenabled(true);
    /**
     * 这里要注意,在用view.measurespec.makemeasurespec(0, view.measurespec.unspecified)
     * 来测量view 的时候,(如果你的布局中包含有 relativelayout )api 为17 或者 低于17 会包空指针异常
     * 解决方法:
     * 1 布局中不要包含relativelayout
     * 2 用 view.measurespec.makemeasurespec(256, view.measurespec.exactly) 好像也可以
     *
     */
    view.measure(view.measurespec.makemeasurespec(0, view.measurespec.unspecified),
        view.measurespec.makemeasurespec(0, view.measurespec.unspecified));
    view.layout(0, 0, view.getmeasuredwidth(), view.getmeasuredheight());
    view.builddrawingcache();
    bitmap bitmap = view.getdrawingcache();
    return bitmap;
  }

 上面就是转换成bitmap 的方法,但是要注意,在用view.measurespec.makemeasurespec(0, view.measurespec.unspecified)

          来测量view 的时候,(如果你的布局中包含有 relativelayout )api 为17 或者 低于17 会包空指针异常。在项目中遇到这个问题

死活不知道是怎么回事,后来在看源码的时候才发现。以下是这个方法的官方解释:

/**
     * creates a measure specification based on the supplied size and mode.
     *
     * the mode must always be one of the following:
     * <ul>
     * <li>{@link android.view.view.measurespec#unspecified}</li>
     * <li>{@link android.view.view.measurespec#exactly}</li>
     * <li>{@link android.view.view.measurespec#at_most}</li>
     * </ul>
     *
     * <p><strong>note:</strong> on api level 17 and lower, makemeasurespec's
     * implementation was such that the order of arguments did not matter
     * and overflow in either value could impact the resulting measurespec.
     * {@link android.widget.relativelayout} was affected by this bug.
     * apps targeting api levels greater than 17 will get the fixed, more strict
     * behavior.</p>
     *
     * @param size the size of the measure specification
     * @param mode the mode of the measure specification
     * @return the measure specification based on size and mode
     */
    public static int makemeasurespec(int size, int mode) {
      if (susebrokenmakemeasurespec) {
        return size + mode;
      } else {
        return (size & ~mode_mask) | (mode & mode_mask);
      }
    }

  在api 17 以上的系统中才修正了这个bug,这里有两个解决方法:

 1 ,布局文件中不要包含relativelayout 布局

 2,用 view.measurespec.makemeasurespec(256, view.measurespec.exactly) 好像也可以

以上就是android 将view 转换为bitmap出现空指针问题解决办法,如有疑问请留言或者到本站社区交流讨论,谢谢大家对本站的支持!