import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
/**
* 三种颜色渐变圆角drawable
*/
public class LinearGradientDrawable extends Drawable {
private Paint mPaint;
private int startColor = Color.parseColor("#f31c79");
private int centerColor = Color.parseColor("#ff00c3");
private int endColor = Color.parseColor("#b30c0c0c");
private float progress;
LinearGradientDrawable(int startColor, int centerColor, int endColor) {
this();
this.startColor = startColor;
this.centerColor = centerColor;
this.endColor = endColor;
}
LinearGradientDrawable() {
mPaint = new Paint();
}
void updateProgress(float progress) {
this.progress = progress;
invalidateSelf();
}
@Override
public void draw(@NonNull Canvas canvas) {
mPaint.reset();
if (startColor != endColor) {
LinearGradient linearGradient = new LinearGradient(0, 0, getBounds().width(), 0,
new int[]{startColor, centerColor, endColor},
new float[]{progress * 0.5f, progress, progress - 0.01f}, Shader.TileMode.CLAMP);
mPaint.setShader(linearGradient);
} else {
mPaint.setColor(startColor);
}
RectF rectF = new RectF(0, 0, getBounds().width(), getBounds().height());
canvas.drawRoundRect(rectF, getBounds().height() / 2f, getBounds().height() / 2f, mPaint);
}
@Override
public void setAlpha(int alpha) {
mPaint.setAlpha(alpha);
}
@Override
public void setColorFilter(@Nullable ColorFilter colorFilter) {
mPaint.setColorFilter(colorFilter);
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
}