1 package sowell.oracle.com.viewdraw; 2 3 import android.content.Context; 4 import android.graphics.Canvas; 5 import android.graphics.Color; 6 import android.graphics.LinearGradient; 7 import android.graphics.Matrix; 8 import android.graphics.Paint; 9 import android.graphics.Shader; 10 import android.util.AttributeSet; 11 import android.widget.TextView; 12 13 14 /** 15 * Created by 94965 on 2017/11/10. 16 */ 17 18 public class MyTextView extends TextView { 19 20 21 22 public int mViewWidth; //记录TextView的宽度 23 public Paint paint1; 24 public Paint paint2; 25 public Paint paint; 26 public LinearGradient linearGradient; //线性渲染器 27 public Matrix matrix; 28 public int translate; 29 30 public void init(){ 31 mViewWidth=0; 32 paint1=new Paint(); 33 paint2=new Paint(); 34 paint=new Paint(); 35 } 36 37 38 public MyTextView(Context context, AttributeSet attrs,int defStyle){ 39 super(context,attrs,defStyle); 40 } 41 42 public MyTextView(Context context,AttributeSet attrs){ 43 super(context,attrs); 44 } 45 46 public MyTextView(Context context){ 47 super(context); 48 } 49 50 @Override 51 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 52 super.onSizeChanged(w, h, oldw, oldh); 53 if(mViewWidth==0){ 54 mViewWidth=getMeasuredWidth(); 55 if(mViewWidth>0){ 56 paint=getPaint(); 57 //定义渐变区域的大小 58 linearGradient=new LinearGradient( 59 0, 60 0, 61 mViewWidth, 62 0, 63 new int[]{ 64 Color.BLUE,0xfffffff, 65 Color.BLUE 66 }, 67 null, 68 Shader.TileMode.CLAMP 69 ); 70 paint.setShader(linearGradient); 71 matrix=new Matrix(); 72 } 73 } 74 } 75 76 @Override 77 protected void onDraw(Canvas canvas) { 78 super.onDraw(canvas); 79 if(matrix!=null){ 80 translate+=mViewWidth/5; 81 if(translate>2*mViewWidth){ 82 translate=-mViewWidth; 83 } 84 matrix.setTranslate(translate,0); 85 linearGradient.setLocalMatrix(matrix); 86 postInvalidateDelayed(100); 87 } 88 } 89 }