Android:将两个叠加的ImageView合并成一个BMP,并保持正确的位置

5
我有两个ImageView。ImageView1是背景图像,ImageView2是较小的图像。ImageView2的位置位于应用程序的中间某个位置。
我想将这两个ImageView组合成一个位于ImageView1之上的位图。
组合过程正常运行,但是ImageView2总是位于bmp文件的左上角。
以下是我用来生成bmp的代码:
    ImageView iv = (ImageView)findViewById(R.id.imageView1);
    ImageView iv2 = (ImageView)findViewById(R.id.imageView2);

    File rootPath = new File(Environment.getExternalStorageDirectory(), "testmerge");

    if (!rootPath.exists()) {
        rootPath.mkdirs();
    }

    Toast.makeText(this, rootPath.getPath(), Toast.LENGTH_LONG).show();
    File dataFile = new File(rootPath, "picture.png");

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

    iv.setDrawingCacheEnabled(true);
    Bitmap b1 = Bitmap.createBitmap(iv.getDrawingCache());
    iv.setDrawingCacheEnabled(false);

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

    iv2.setDrawingCacheEnabled(true);
    Bitmap b2 = Bitmap.createBitmap(iv2.getDrawingCache());
    iv2.setDrawingCacheEnabled(false);        

    Bitmap bmOverlay = Bitmap.createBitmap(b1.getWidth(), b1.getHeight(), b1.getConfig());
    Canvas canvas = new Canvas(bmOverlay);
    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setFilterBitmap(true);
    paint.setDither(true);

    canvas.drawBitmap(b1, 0, 0, null);
    canvas.drawBitmap(b2, 0, 0, null);

    try {
        FileOutputStream out = new FileOutputStream(dataFile, false);
        bmOverlay.compress(CompressFormat.PNG, 95, out);
    } catch (IOException e) {
        e.printStackTrace();
    }

请问如何调整最终的位图文件位置,使得ImageView在应用中显示时与原位置相同?

谢谢。


@Kintaro,你能帮我解决这个问题吗?你是如何完成这个任务的? - Erum
我知道这个问题很久以前就被问过了,但也许你仍然可以帮助我。我正在尝试使用你的“合并”方法,但我的问题是,.Compress方法要求一个System.IO.Stream而不是Java.IO.FileOutputStream。 - Aiko West
1个回答

3

只需创建一个FrameLayout,并在其中包含两个ImageView。它会自然地将第二个图像覆盖在第一个图像上。

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ImageView
        android:id="@+id/main_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/main" />

    <ImageView
        android:id="@+id/overlay_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/overlay" />

</FrameLayout>

您可以将重力应用于图像的中心或其他位置进行对齐。


谢谢回复。我的问题是最终的位图(bmOverlay)包含了两个ImageView,但是顶部的ImageView始终在位图的左上角。您的意思是FrameLayout会自动为我做到这一点(当我从FrameLayout创建位图时)吗? - Kintarō
如果您将两个子元素放在帧布局中,它们将精确地重叠在一起,除非您添加其他布局属性来避免这种情况发生(例如使容器match_parent,并在每个子元素上设置不同的gravity属性)。 - Jeffrey Blattman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接