Android 渐变圆环等待
时间: 2023-10-13 17:22:17 浏览: 37
您可以使用Android中的Canvas和Paint类来创建渐变圆环等待效果。下面是一个示例代码:
```
public class GradientRingView extends View {
private Paint mPaint;
private int mRadius;
private int mStrokeWidth;
private int mColors[];
private int mColorIndex;
public GradientRingView(Context context) {
super(context);
init();
}
public GradientRingView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public GradientRingView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mStrokeWidth = 10;
mPaint.setStrokeWidth(mStrokeWidth);
mColors = new int[]{Color.RED, Color.GREEN, Color.BLUE};
mColorIndex = 0;
post(new Runnable() {
@Override
public void run() {
startAnimation();
}
});
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
mRadius = Math.min(width, height) / 2 - mStrokeWidth / 2;
setMeasuredDimension(width, height);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int cx = getWidth() / 2;
int cy = getHeight() / 2;
mPaint.setShader(new SweepGradient(cx, cy, mColors, null));
canvas.drawCircle(cx, cy, mRadius, mPaint);
}
private void startAnimation() {
ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
animator.setDuration(2000);
animator.setInterpolator(new LinearInterpolator());
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float fraction = animation.getAnimatedFraction();
if (fraction == 1) {
mColorIndex++;
if (mColorIndex >= mColors.length) {
mColorIndex = 0;
}
}
mPaint.setColor((Integer) new ArgbEvaluator().evaluate(fraction, mColors[mColorIndex], mColors[(mColorIndex + 1) % mColors.length]));
postInvalidate();
}
});
animator.start();
}
}
```
在布局文件中使用该View即可创建渐变圆环等待效果:
```
<com.example.GradientRingView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
```