如何将图像保存为RelativeLayout

时间:2012-10-20 06:49:01

标签: android

如何将相对布局保存为位图图像....? 在运行时我将图像添加到相对布局..然后如何将其保存为位图图像。

我对这个概念一无所知......请为此提出解决方案。

谢谢。

2 个答案:

答案 0 :(得分:8)

创建XML文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:id="@+id/rlid"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"/>

然后在您的活动中使用此代码:

View content = findViewById(R.id.rlid);
content.setDrawingCacheEnabled(true);
Bitmap bitmap = content.getDrawingCache();
File file = new File("/sdcard/" + yourimagename + ".png");
try {
    if (!file.exists()) {
        file.createNewFile();
    }
    FileOutputStream ostream = new FileOutputStream(file);
    bitmap.compress(CompressFormat.PNG, 10, ostream);
    ostream.close();
    content.invalidate();
} catch (Exception e) {
    e.printStackTrace();
} finally {
        content.setDrawingCacheEnabled(false);
}

答案 1 :(得分:0)

试试这个: 将一个按钮放在相对布局中,然后执行此处理存储在sdcard中的图像

        btn1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            view.setDrawingCacheEnabled(true);
            view.buildDrawingCache();
            bm = view.getDrawingCache();

            String root = Environment.getExternalStorageDirectory()
                    .toString();
            File myDir = new File(root + "/_images");
            myDir.mkdirs();
            Random generator = new Random();
            int n = 10000;
            n = generator.nextInt(n);
            String fname = "Image-" + n + ".jpg";
            file = new File(myDir, fname);

            Log.i(TAG, "" + file);

            if (file.exists())
                file.delete();
            try {
                FileOutputStream out = new FileOutputStream(file);
                bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
                out.flush();
                out.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
相关问题