在android中叠加两个图像以设置图像视图 [英] overlay two images in android to set an imageview

查看:30
本文介绍了在android中叠加两个图像以设置图像视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的应用程序中叠加两个图像,但它们似乎在我的 canvas.setBitmap() 行崩溃.我做错了什么?

I am trying to overlay two images in my app, but they seem to crash at my canvas.setBitmap() line. What am I doing wrong?

private void test() {
    Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.t);
    Bitmap mBitmap2 = BitmapFactory.decodeResource(getResources(), R.drawable.tt);
    Bitmap bmOverlay = Bitmap.createBitmap(mBitmap.getWidth(), mBitmap.getHeight(), mBitmap.getConfig());
    Canvas canvas = new Canvas();
    canvas.setBitmap(bmOverlay);
    canvas.drawBitmap(mBitmap, new Matrix(), null);
    canvas.drawBitmap(mBitmap2, new Matrix(), null);
    testimage.setImageBitmap(bmOverlay);
}

推荐答案

你可以跳过复杂的 Canvas 操作,完全使用 Drawables 来完成,使用 LayerDrawable.您有两个选择之一:您可以在 XML 中定义它,然后简单地设置图像,或者您可以在代码中动态配置 LayerDrawable.

You can skip the complex Canvas manipulation and do this entirely with Drawables, using LayerDrawable. You have one of two choices: You can either define it in XML then simply set the image, or you can configure a LayerDrawable dynamically in code.

解决方案 #1(通过 XML):

Solution #1 (via XML):

创建一个新的 Drawable XML 文件,我们称之为 layer.xml:

Create a new Drawable XML file, let's call it layer.xml:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/t" />
    <item android:drawable="@drawable/tt" />
</layer-list>

现在使用该 Drawable 设置图像:

Now set the image using that Drawable:

testimage.setImageDrawable(getResources().getDrawable(R.layout.layer));

解决方案#2(动态):

Solution #2 (dynamic):

Resources r = getResources();
Drawable[] layers = new Drawable[2];
layers[0] = r.getDrawable(R.drawable.t);
layers[1] = r.getDrawable(R.drawable.tt);
LayerDrawable layerDrawable = new LayerDrawable(layers);
testimage.setImageDrawable(layerDrawable);

(我还没有测试过这段代码,所以可能有错误,但是这个大纲应该可以工作.)

(I haven't tested this code so there may be a mistake, but this general outline should work.)

这篇关于在android中叠加两个图像以设置图像视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆