CircleArcView .java
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.LinearInterpolator;
/**
* by.benny
* time 2018/10/14
* descriptions: 旋转的弧形进度条
*/
public class CircleArcView extends View {
Paint paint;
private ObjectAnimator objectAnimator;
private int STATE_STOP = 0;
private int STATE_START = 1;
private int STATE_PAUSE = 2;
private int state;
public CircleArcView(Context context) {
super(context);
init();
}
public CircleArcView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CircleArcView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
paint = new Paint();
paint.setStrokeWidth(8);
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.RED);
// 消除锯齿
paint.setAntiAlias(true);
startAnim();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int w = getWidth();
int h = getHeight();
int radius = Math.min(w, h) / 2;
//画圆
//canvas.drawCircle(w/2,h/2,radius-50,paint);
int arcLeng = 10;
//画弧
int sX=w * arcLeng / w;//弧形的起点X
int sY=h * arcLeng / h;//弧形的起点Y
int eX=w * (w-arcLeng) / w;//弧形的终点X
int eY=h * (h-arcLeng) / h;//弧形的终点Y
RectF oval = new RectF(sX, sY, eX, eY);
canvas.drawArc(oval, 0, 160, false, paint);
invalidate();
}
private void startAnim() {
state = STATE_STOP;
objectAnimator = ObjectAnimator.ofFloat(this, "rotation", 0f, 360f);
//添加旋转动画,旋转中心默认为控件中点
objectAnimator.setDuration(3000);
//设置动画时间
objectAnimator.setInterpolator(new LinearInterpolator());
//动画时间线性渐变
objectAnimator.setRepeatCount(ObjectAnimator.INFINITE);
objectAnimator.setRepeatMode(ObjectAnimator.RESTART);
play();
}
public void play() {
if (state == STATE_STOP) {
objectAnimator.start();
//动画开始
state = STATE_START;
} else if (state == STATE_PAUSE) {
objectAnimator.resume();
//动画重新开始
state = STATE_START;
} else if (state == STATE_START) {
objectAnimator.pause();
// 动画暂停
state = STATE_PAUSE;
}
}
public void stop() {
objectAnimator.end();
// 动画结束
state = STATE_STOP;
}
}
circle_arc_layout.xml
<FrameLayout
android:id="@+id/frameLayout"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/cpb">
<com.***.***.widget.CircleArcView
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<ImageView
android:src="@drawable/ic_circle_bg"
android:layout_width="match_parent"
android:scaleType="fitXY"
android:layout_margin="@dimen/d5"
android:layout_height="match_parent" />
</FrameLayout>