Android 自定义 View 实现带阴影效果的转椭圆圈圈加载动画
要实现带有光影效果的转椭圆圈圈的加载中动画,可以自定义一个 View,并使用 Canvas 和 Paint 来绘制动画效果。
首先,创建一个自定义的 View 类,继承自 View,并重写 onDraw 方法:
public class LoadingView extends View {
private int mWidth;
private int mHeight;
private float mRadius;
private float mStartAngle;
private float mSweepAngle;
private Paint mPaint;
private int mShadowColor;
private int mCircleColor;
public LoadingView(Context context) {
super(context);
init();
}
public LoadingView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public LoadingView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mShadowColor = Color.parseColor("#E8E8E8");
mCircleColor = Color.parseColor("#FF4081");
mPaint = new Paint();
mPaint.setAntiAlias(true);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mWidth = w;
mHeight = h;
// 计算圆的半径
mRadius = Math.min(mWidth, mHeight) / 2f * 0.8f;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 绘制阴影
mPaint.setColor(mShadowColor);
mPaint.setStyle(Paint.Style.FILL);
canvas.drawCircle(mWidth / 2f, mHeight / 2f, mRadius, mPaint);
// 绘制圆圈
mPaint.setColor(mCircleColor);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(10f);
RectF rectF = new RectF(mWidth / 2f - mRadius, mHeight / 2f - mRadius,
mWidth / 2f + mRadius, mHeight / 2f + mRadius);
canvas.drawArc(rectF, mStartAngle, mSweepAngle, false, mPaint);
// 更新角度
mStartAngle += 10;
mSweepAngle += 5;
// 重绘
invalidate();
}
}
在 init 方法中,我们设置了阴影颜色和圆圈颜色,并创建了一个 Paint 对象用于绘制图形。
在 onSizeChanged 方法中,我们根据 View 的尺寸计算出圆的半径。
在 onDraw 方法中,我们先绘制阴影,然后绘制圆圈。使用 RectF 来定义圆弧的外接矩形,使用 drawArc 方法绘制圆弧。
最后,我们在 onDraw 方法中更新圆弧的起始角度和扫过角度,并调用 invalidate 方法来触发重绘,从而实现动画效果。
要使用这个自定义的 View,可以在布局文件中添加一个 LoadingView:
<com.example.loadingview.LoadingView
android:layout_width="200dp"
android:layout_height="200dp" />
这样就可以在布局中显示带有光影效果的转椭圆圈圈的加载中动画了。
原文地址: https://www.cveoy.top/t/topic/qFHt 著作权归作者所有。请勿转载和采集!