1

我有一个名为的相对布局rel,它动态地向它添加一个 imageview,如下所示:

     rel.setBackgroundResource(R.drawable.bg_share_one);

                RelativeLayout.LayoutParams p1 = new RelativeLayout.LayoutParams(921, 691);
                p1.leftMargin = 30;
                p1.topMargin = 30;

                ImageView img = new ImageView(this);
                img.setLayoutParams(p1);
                myBitmap = BitmapFactory.decodeFile(files[0].getAbsolutePath(), option1);
                img.setImageBitmap(myBitmap);

                rel.addView(img);
                saveCompareImage();

然后我调用此方法来截取该相对布局的屏幕截图,但它添加的图像视图未显示在位图中:

 protected void saveCompareImage() {
    // TODO Auto-generated method stub

    rel.setDrawingCacheEnabled(true);
    try {

        File file = new File("/sdcard/LC/compare.jpg");
        file.createNewFile();
        Bitmap bm = rel.getDrawingCache();
        FileOutputStream ostream = new FileOutputStream(file);
        bm.compress(Bitmap.CompressFormat.JPEG, 80, ostream);
        ostream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
4

2 回答 2

1

也许您启用了硬件加速?的文档setDrawingCacheEnabled()说明在这种情况下渲染的方式不同:

打开硬件加速时,启用绘图缓存对渲染没有影响,因为系统使用不同的加速机制来忽略该标志。如果您想为视图使用位图,即使启用了硬件加速,请参阅 setLayerType(int, android.graphics.Paint) 以获取有关如何启用软件和硬件层的信息。

试试看setLayerType(LAYER_TYPE_SOFTWARE, null)什么的。

于 2012-12-12T20:44:55.583 回答
0

问题不是调用措施:这有效:

protected void saveCompareImage() {
    // TODO Auto-generated method stub

    rel.setDrawingCacheEnabled(true);

    try {
        File file = new File("/sdcard/LC/compare.jpg");
        file.createNewFile();   
        Bitmap bitmap;
        rel.setDrawingCacheEnabled(true);
        rel.measure(MeasureSpec.makeMeasureSpec(rel.getLayoutParams().width, MeasureSpec.EXACTLY),
                MeasureSpec.makeMeasureSpec(rel.getLayoutParams().height, MeasureSpec.EXACTLY));
        rel.layout(0, 0, rel.getMeasuredWidth(), rel.getMeasuredHeight());

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


        FileOutputStream ostream = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, ostream);
        ostream.close();
    } catch (Exception e) {
        Log.v("ERRRO","e:"+e);
    }
}
于 2012-12-12T21:48:57.343 回答