一、创建LayerDrawable和使用
一个LayerDrawable是一个可以管理一组drawable对象的drawable。在LayerDrawable的drawable资源按照列表的顺序绘制,列表的最后一个drawable绘制在最上层。
它所包含的一组drawable资源用多个<item>元素表示,一个<item>元素代表一个drawable资源。
-
文件位置:
-
res/drawable/filename.xml
文件名最为资源ID
编译数据类型:
-
指向LayerDrawable的指针
资源引用
-
In Java:
R.drawable.filename
In XML:@[package:]drawable/filename
语法:
- <?xml version="1.0" encoding="utf-8"?>
- <layer-list
- xmlns:android="http://schemas.android.com/apk/res/android" >
- <item
- android:drawable="@[package:]drawable/drawable_resource"
- android:id="@[+][package:]id/resource_name"
- android:top="dimension"
- android:right="dimension"
- android:bottom="dimension"
- android:left="dimension" />
- </layer-list>
-
元素:
例子:在xml文件中定义layerDrawable,然后使用
-
<span class="pun"></span><?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/black_lotus" android:left="20dp" android:top="20dp"> </item> <item android:drawable="@drawable/black_lotus" android:left="40dp" android:top="40dp"> </item> <item android:drawable="@drawable/black_lotus" android:left="60dp" android:top="60dp"> </item> </layer-list><span class="tag"></span>
<span class="tag"><ImageView</span><span class="pln"> </span><span class="atn">android:layout_height</span><span class="pun">=</span><span class="atv">"wrap_content"</span><span class="pln"> </span><span class="atn">android:layout_width</span><span class="pun">=</span><span class="atv">"wrap_content"</span><span class="pln"> </span><span class="atn">android:src</span><span class="pun">=</span><span class="atv">"@drawable/layers"</span><span class="pln"> </span><span class="tag">/></span>
在代码中定义然后使用
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.black_lotus);
- Drawable[] drawables=new Drawable[3];
- // drawables[0]=new PaintDrawable(Color.BLACK);
- // drawables[1]=new PaintDrawable(Color.BLUE);
- drawables[0]=new BitmapDrawable(bitmap);
- drawables[1]=new BitmapDrawable(bitmap);
- drawables[2]=new BitmapDrawable(bitmap);
- LayerDrawable layer=new LayerDrawable(drawables);
- layer.setLayerInset(0, 20, 20, 0, 0);
- layer.setLayerInset(1, 40, 40, 0, 0);
- layer.setLayerInset(2, 60, 60, 0, 0);
- ImageView imageView=(ImageView)findViewById(R.id.imgView);
- imageView.setImageDrawable(layer);
- }
- <ImageView
- android:id="@+id/imgView"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"/>
![](https://img-my.csdn.net/uploads/201211/13/1352778472_1182.png)