温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

在Android中将view 转换为Bitmap出现空指针如何解决

发布时间:2021-02-24 16:07:32 来源:亿速云 阅读:193 作者:戴恩恩 栏目:移动开发

这篇文章主要介绍了在Android中将view 转换为Bitmap出现空指针如何解决,此处通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考价值,需要的朋友可以参考下:

Android是什么

Android是一种基于Linux内核的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由美国Google公司和开放手机联盟领导及开发。

 首先是转换 的代码:

/**
   * 将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出现空指针如何解决的文章就介绍到这了,更多相关在Android中将view 转换为Bitmap出现空指针如何解决的内容请搜索亿速云以前的文章或继续浏览下面的相关文章希望大家以后多多支持亿速云!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI