首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >imageview DrawingCache返回null

imageview DrawingCache返回null
EN

Stack Overflow用户
提问于 2013-01-07 17:08:46
回答 2查看 1.6K关注 0票数 1

我使用的是DrawingCache,但它提供了NullPointerException

我的代码如下:

代码语言:javascript
复制
    myImageView.setDrawingCacheEnabled(true);

    myImageView.buildDrawingCache();
    resized = myImageView.getDrawingCache();        
    btnSave.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            String save_location = Environment
                    .getExternalStorageDirectory().getAbsolutePath()
                    + "/EditedImage";
            File dir = new File(save_location);
            if (!dir.exists())
                dir.mkdirs();
            File f = new File(dir, TEMP_PHOTO_FILE);
            FileOutputStream out;
            try {
                out = new FileOutputStream(f);
                resized.compress(Bitmap.CompressFormat.PNG, 90, out);

                out.flush();
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

错误出现在onClick。

我的logcat是

这里面缺少了什么?

EN

回答 2

Stack Overflow用户

发布于 2013-01-07 17:20:40

试试这个考试:

代码语言:javascript
复制
myImageView.setDrawingCacheEnabled(true);

myImageView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 
            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
myImageView.layout(0, 0, v.getMeasuredWidth(), myImageView.getMeasuredHeight()); 

myImageView.buildDrawingCache(true);


Bitmap b = Bitmap.createBitmap(myImageView.getDrawingCache());
myImageView.setDrawingCacheEnabled(false); // clear drawing cache

更新:

另一种方法是为位图创建画布,然后调用view.draw( Canvas ),如下所示:

代码语言:javascript
复制
 public static Bitmap loadBitmapFromView(View v) {
         Bitmap b = Bitmap.createBitmap( v.getLayoutParams().width, v.getLayoutParams().height,              Bitmap.Config.ARGB_8888);                


         Canvas c = new Canvas(b);
         v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
         v.draw(c);
         return b;
    }
票数 1
EN

Stack Overflow用户

发布于 2013-01-07 17:43:07

在绘制到屏幕上之前,每个视图都需要执行一些步骤,例如,测量和布局。因此,当您在Activity.onCreate()中调用getDrawingCache()时,视图尚未绘制。

将以下两行放入onclick方法中。

代码语言:javascript
复制
myImageView.buildDrawingCache();
resized = myImageView.getDrawingCache();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14192799

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档