在Android中设置一个ImageView的叠加两个图像 [英] overlay two images in android to set an imageview
问题描述
我试图将两张图像在我的应用程序,但他们似乎崩溃在我的 canvas.setBitmap()
行。我究竟做错了什么?
私人无效测试(){
位图mBitmap = BitmapFactory.de codeResource(getResources(),R.drawable.t);
位图mBitmap2 = BitmapFactory.de codeResource(getResources(),R.drawable.tt);
位图bmOverlay = Bitmap.createBitmap(mBitmap.getWidth(),mBitmap.getHeight(),mBitmap.getConfig());
帆布油画=新的Canvas();
canvas.setBitmap(bmOverlay);
canvas.drawBitmap(mBitmap,新的Matrix(),NULL);
canvas.drawBitmap(mBitmap2,新的Matrix(),NULL);
testimage.setImageBitmap(bmOverlay);
}
您可以跳过复杂的帆布操纵和做完全用可绘,使用<一个href="http://developer.android.com/intl/fr/reference/android/graphics/drawable/LayerDrawable.html"><$c$c>LayerDrawable$c$c>.你有两个选择:你可以在XML 定义它,然后简单地设置图像,或者你可以配置一个 LayerDrawable
动态在code。
解决方案#1(通过XML):
创建一个新的可绘制的XML文件,姑且称之为的layer.xml
:
&LT;层列表的xmlns:机器人=http://schemas.android.com/apk/res/android&GT;
&LT;项目机器人:可绘制=@可绘制/吨/&GT;
&LT;项目机器人:可绘制=@可绘制/ TT/&GT;
&LT; /层列表&gt;
现在使用设置图像绘制对象:
testimage.setImageDrawable(getResources()getDrawable(R.layout.layer)。);
解决方案#2(动态):
资源R = getResources();
绘制对象[]层=新绘制对象[2];
层[0] = r.getDrawable(R.drawable.t);
层[1] = r.getDrawable(R.drawable.tt);
LayerDrawable layerDrawable =新LayerDrawable(层);
testimage.setImageDrawable(layerDrawable);
(我没有测试此code所以有可能是一个错误,但是这个大纲应该工作。)
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);
}
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.
Solution #1 (via 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>
Now set the image using that Drawable:
testimage.setImageDrawable(getResources().getDrawable(R.layout.layer));
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中设置一个ImageView的叠加两个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!