Secondtime上Imageview.getDrawingCache中的空指针异常

时间:2014-04-23 05:01:11

标签: android bitmap imageview drawingcache

            View vvv=mViewFlipper.getCurrentView();             
            RelativeLayout rrr=(RelativeLayout)vvv;
            ImageView img=(ImageView) rrr.getChildAt(0);
            img.setRotation(90); 

            img.setDrawingCacheEnabled(true);
            img.buildDrawingCache();                
            Bitmap bitmap =img.getDrawingCache();             
            img.destroyDrawingCache();
            img.setDrawingCacheEnabled(false);

            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            Matrix matrix = new Matrix();
            matrix.postRotate(90);
            Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
            BitmapDrawable bmd = new BitmapDrawable(rotatedBitmap); 
            rrr.removeViewAt(0);
            ImageView img_new=new ImageView(ImageSlideShow.this);
            img_new.setImageDrawable(bmd);
            img_new.setScaleType(ScaleType.CENTER);
            rrr.addView(img_new, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

我已使用以上代码在ViewFlipper中旋转图像 第一次执行但第二次返回NullPointerException ... 错误行:

Bitmap bitmap =Bitmap.createBitmap(img.getDrawingCache());

2 个答案:

答案 0 :(得分:0)

嗨使用此代码,希望这可行

基本上你的图像视图为空,所以首先将其视为

ImageView img= new ImageView();
img=(ImageView) rrr.getChildAt(0);
        img.setRotation(90); 

img.setDrawingCacheEnabled(true);
        img.buildDrawingCache(); 
if(img.isDrawingCacheEnabled()){               
        Bitmap bitmap =img.getDrawingCache(true);             
}img.destroyDrawingCache();
        img.setDrawingCacheEnabled(false);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100,
                                bao);

        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Matrix matrix = new Matrix();
        matrix.postRotate(90);
        Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        BitmapDrawable bmd = new BitmapDrawable(rotatedBitmap); 
        rrr.removeViewAt(0);
        ImageView img_new=new ImageView(ImageSlideShow.this);
        img_new.setImageDrawable(bmd);
        img_new.setScaleType(ScaleType.CENTER);
        rrr.addView(img_new, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

答案 1 :(得分:0)

我得到了解决方案这个问题

ImageView img=(ImageView) rrr.getChildAt(0);            
                Matrix matrix = new Matrix(); 
                matrix.set(img.getImageMatrix());
                matrix.postRotate(90, img.getWidth() / 2, img.getHeight() / 2);
                img.setImageMatrix(matrix); 

上面的代码完成图像旋转工作,你必须在你的imageview中设置android:scaleType =“matrix”。