我有一个类似下面的 png 图像,我需要根据它的容量填充它的背景颜色。
例如,如果油箱的油量占其容量的 %100%,则背景应为黄色,如果油箱容量为 %25,则背景应为 %25% 黄色和 %75 透明。
假设这是游戏中的生命条。
这就是我的布局,只是线性布局中的一个简单 ImageView 。 有什么方法可以使用动画、剪辑或其他方式实现这一目标吗?
<ImageView
android:id="@+id/ivOilTank"
android:layout_width="0dp"
android:src="@mipmap/oilTank"
android:layout_height="match_parent"
android:layout_weight="1">
最佳答案
更改您的布局 xml 以包含-
<FrameLayout
android:layout_width="150dp"
android:layout_height="wrap_content"
android:background="@android:color/black"
>
<View
android:id="@+id/percent_highlight"
android:layout_width="0dp"
android:layout_height="match_parent"
/>
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@mipmap/oilTank"
/>
</FrameLayout>
现在无论你想突出显示图像的特定百分比 -
View highlight = findViewById(R.id.percent_highlight);
highlight.setBackgroundResource(<Color_id>);//Any color you want to set
ViewGroup.LayoutParams layoutParams = highlight.getLayoutParams();
layoutParams.width = (int) (dpToPixel(150) * 25 / 100.0f);//If you want to set 25%
highlight.setLayoutParams(layoutParams);
其中 dpToPixel()
将 dp 转换为像素 -
public int dpToPixel(float dp) {
final float scale = getResources().getDisplayMetrics().density;
return (int) (dp * scale + 0.5f);
}
关于android - 如何像进度条一样填充imageview的背景色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36072824/