要在Android ProgressBar上实现颜色渐变,您可以使用以下方法:
GradientProgressBar
的类并继承ProgressBar
。import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.widget.ProgressBar;
public class GradientProgressBar extends ProgressBar {
private Paint paint;
private LinearGradient linearGradient;
public GradientProgressBar(Context context) {
super(context);
init();
}
public GradientProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public GradientProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
paint = new Paint();
paint.setAntiAlias(true);
linearGradient = new LinearGradient(0, 0, getWidth(), getHeight(), Color.RED, Color.BLUE, Shader.TileMode.CLAMP);
paint.setShader(linearGradient);
}
@Override
protected void onDraw(Canvas c) {
super.onDraw(c);
paint.setAlpha(getAlpha());
c.drawRect(0, 0, getWidth(), getHeight(), paint);
}
}
GradientProgressBar
。<your.package.name.GradientProgressBar
android:id="@+id/gradientProgressBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:indeterminate="false"
android:progress="50"/>
GradientProgressBar gradientProgressBar = findViewById(R.id.gradientProgressBar);
gradientProgressBar.setProgress(50); // 设置进度为50%
现在,您的进度条将具有从红色到蓝色的渐变颜色。您可以根据需要自定义渐变颜色和方向。