Android开发:能否为layer-list的item设置类似ImageView的fitCenter缩放效果?
当然可以用layer-list实现类似ImageButton的fitCenter效果,完全不需要自定义BitmapDrawable类,咱们调整一下你的layer-list配置就能搞定!
先看你提供的效果截图:
你当前的实现代码
使用layer-list的Button
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/button_yellow"/> <item android:top="5dp" android:bottom="5dp" android:left="5dp" > <bitmap android:src="@drawable/Export_hell_seidel_steiner" android:gravity="center"/> </item> </layer-list> <Button android:layout_width="341dp" android:layout_height="143dp" android:layout_margin="3dp" android:background="@drawable/layer1" android:onClick="onClick" android:text="" />
你的ImageButton实现
<ImageButton android:layout_width="299dp" android:layout_height="129dp" android:background="@drawable/button_yellow" android:padding="5dp" android:scaleType="fitCenter" android:src="@drawable/Export_hell_seidel_steiner" />
解决方案:修改layer-list的bitmap配置
问题出在你原来的<bitmap>标签只设置了gravity="center",这只会让图片居中,但不会按比例缩放适配。要实现fitCenter的效果,只需要给<bitmap>添加两个关键属性:
android:scale="fitCenter":核心属性,让图片按比例缩放至适配可用空间android:gravity="center|clip_vertical|clip_horizontal":确保图片居中,超出部分被裁剪
另外建议给图标层的item加上android:right="5dp",让左右内边距一致,和ImageButton的padding="5dp"视觉对齐。
修改后的layer-list代码:
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 背景按钮层 --> <item android:drawable="@drawable/button_yellow"/> <!-- 图标层:实现fitCenter效果 --> <item android:top="5dp" android:bottom="5dp" android:left="5dp" android:right="5dp"> <bitmap android:src="@drawable/Export_hell_seidel_steiner" android:gravity="center|clip_vertical|clip_horizontal" android:scale="fitCenter"/> </item> </layer-list>
这样调整后,你的Button用这个layer-list作为背景,就能实现和ImageButton完全一致的fitCenter缩放效果,完全不需要自定义任何Drawable类~
内容的提问来源于stack exchange,提问作者user5636914
相关产品推荐
相关产品推荐

