时间:2022-06-21 10:01:29 | 栏目:Android代码 | 点击:次
前几天看了一位字节Android工程师的一篇博客,他实现的是歌词上下滚动的效果,实现的关键就是定义一个偏移量,然后根据情况去修改这个值,最后触发View的重绘来达到效果。于是今天根据这个思路来写一篇简单的文章。欢迎留言
在这之前呢,还是得简单描述一下自定义view中的一些准备工作
@Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mWidth = w; mHeight = h; useWidth = mWidth; if (mWidth > mHeight) { useWidth = mHeight; } }
private void initPaint() { //初始化 mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setStyle(Paint.Style.STROKE); mPaint.setColor(0x88FF0000); mPaint.setStrokeWidth(4); //初始化 mFramePaint = new Paint(); mFramePaint.setAntiAlias(true); mFramePaint.setStyle(Paint.Style.STROKE); mFramePaint.setStrokeWidth(0); }
这个案例因为时间关系就不自定义属性了,更多请参考本人以前的文章:Android自定义view之围棋动画
此方法中共有五个参数
通过改变sweepAngle(上述方法第三个参数)的值,然后刷新View来达到效果
代码如下:
mSweep += SWEEP_INC; if (mSweep > 360) { mSweep -= 360; } //刷新View invalidate();
源码
MySampleView.java
public class MySampleView extends View { private int mWidth; private int mHeight; private int useWidth, minwidth; private Paint mPaint; private Paint mFramePaint; private RectF mBigOval; private float mStart; private float mSweep; private static final float SWEEP_INC = 2; public MySampleView(Context context) { super(context); } public MySampleView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public MySampleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public MySampleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } private void init() { initPaint(); } private void initPaint() { //初始化 mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setStyle(Paint.Style.STROKE); mPaint.setColor(0x88FF0000); mPaint.setStrokeWidth(4); //初始化 mFramePaint = new Paint(); mFramePaint.setAntiAlias(true); mFramePaint.setStyle(Paint.Style.STROKE); mFramePaint.setStrokeWidth(0); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mWidth = w; mHeight = h; useWidth = mWidth; if (mWidth > mHeight) { useWidth = mHeight; } } @Override protected void onDraw(Canvas canvas) { init(); //定义一个最小标识 minwidth = useWidth / 10; mBigOval = new RectF(minwidth, minwidth, minwidth*9, minwidth*9); //绘制背景 canvas.drawColor(Color.WHITE); canvas.drawRect(mBigOval, mFramePaint); canvas.drawArc(mBigOval, mStart, mSweep, true, mPaint); mSweep += SWEEP_INC; if (mSweep > 360) { mSweep -= 360; } //刷新View invalidate(); } }