这篇文章主要为大家展示了“android如何自定义view仿今日头条加载文字变色效果”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“android如何自定义view仿今日头条加载文字变色效果”这篇文章吧。
具体内容如下
package com.loading; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.os.Handler; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; /** * Created by zhouguizhijxhz on 2018/5/25. */ public class LoadingView extends View{ private Paint loadPaint; private Paint paint; private String text = "今日头条"; private float percent; private Handler handler = new Handler(); public LoadingView(Context context) { this(context,null); } public LoadingView(Context context, @Nullable AttributeSet attrs) { this(context, attrs,0); } public LoadingView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initPaint(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { Rect bounds = new Rect(); paint.getTextBounds(text, 0, text.length(), bounds); setMeasuredDimension(bounds.width(),bounds.height()); } private void initPaint() { paint = new Paint(); paint.setColor(Color.parseColor("#999999")); paint.setTextSize(60); loadPaint = new Paint(); loadPaint.setStyle(Paint.Style.FILL); loadPaint.setColor(0x70ffffff); } @Override protected void onDraw(Canvas canvas) { drawText(canvas); drawLine(canvas); } private void drawLine(Canvas canvas) { if(null==canvas){ return; } canvas.save(); Rect bounds = new Rect(); paint.getTextBounds(text, 0, text.length(), bounds); Rect rect = new Rect(0, 0, (int) (bounds.width()*percent), bounds.height()); canvas.clipRect(rect); canvas.drawRect(rect,loadPaint); canvas.restore(); handler.postDelayed(new Runnable() { @Override public void run() { if(percent>=1.0){ percent=0; }else{ percent+=0.05f; } postInvalidate(); } },200); } private void drawText(Canvas canvas) { if(null==canvas){ return; } Paint.FontMetricsInt fm = paint.getFontMetricsInt(); canvas.drawText(text, getWidth() / 2 - paint.measureText(text) / 2, getHeight() / 2 - (fm.bottom + fm.top) / 2, paint); } @Override protected void onWindowVisibilityChanged(int visibility) { if(visibility==View.VISIBLE){ percent+=0.05f; invalidate(); } } }
效果:
以上是“android如何自定义view仿今日头条加载文字变色效果”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。