欢迎来到代码驿站!

Android代码

当前位置:首页 > 移动开发 > Android代码

android自定义view仿今日头条加载文字变色效果

时间:2021-07-25 08:38:51|栏目:Android代码|点击:

本文实例为大家分享了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();
  }
 }
}

效果:

如果要达到头条那么好看,叫你们美工给你们2个颜色值就可以了。

上一篇:Android Handler工作原理解析

栏    目:Android代码

下一篇:Android中ExpandableListView使用示例详解

本文标题:android自定义view仿今日头条加载文字变色效果

本文地址:http://www.codeinn.net/misctech/161217.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有