android - 如何像进度条一样填充imageview的背景色?

标签 android android-layout android-animation

我有一个类似下面的 png 图像,我需要根据它的容量填充它的背景颜色。

例如,如果油箱的油量占其容量的 %100%,则背景应为黄色,如果油箱容量为 %25,则背景应为 %25% 黄色和 %75 透明。

假设这是游戏中的生命条。

enter image description here

这就是我的布局,只是线性布局中的一个简单 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/

相关文章:

java - 访问 fragment 中的 Activity 变量

android - 如何获取指定位置的URI?

android - Android 中的本地主机

Android:在定义的时间后使 View 消失的最佳方法

android - 动画师相当于新动画中的 applyTransformation

Android : A/libc: Fatal signal 11 (SIGSEGV), 代码 1,tid 18372 中的故障地址 0x8

android - 如何将 WiFi 级别(即 -45 、 -88 )转换为百分比?

Android NavigationView( Material 支持库)无法与状态栏正确交互

android - 将带有自定义布局的 Toast 放在屏幕底部

android - 结束动画事件android