1. Write a class that inherits View
2. onDraw override method and the method onSizeChanged
3. code is as follows:
private Paint paint1;
private Paint mPaint;
private int mViewWidth;
private LinearGradient mlinearGradient;
private int mTranslate;//水平方向上平移的距离
private Matrix gradientMatrix;
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (gradientMatrix != null) {
mTranslate += mViewWidth / 5;
//每次刷新view平移一点,如果到头就重新返回在开始平移
if (mTranslate >2*mViewWidth){
mTranslate = -mViewWidth;
}
gradientMatrix.setTranslate(mTranslate,0);
mlinearGradient.setLocalMatrix(gradientMatrix);
postInvalidateDelayed(100);
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (mViewWidth == 0){
mViewWidth = getMeasuredWidth();
if (mViewWidth > 0){
mPaint = getPaint();
mlinearGradient = new LinearGradient(0
, 0
, mViewWidth
, 0
, new int[]{Color.BLUE,0xffffffff,Color.BLUE}
, null
, Shader.TileMode.CLAMP);
}
mPaint.setShader(mlinearGradient);
gradientMatrix = new Matrix();
}
}
public void initPaint(){
paint1 = new Paint();
paint1.setColor(Color.BLUE);
paint1.setStyle(Paint.Style.FILL);
}
The key point is to use getPaint () method to get Paint target current draw of TextView, and to the paint object setting LinearGradient properties, in onDraw method, by a matrix manner to continuously translate gradient, so as to draw the text is to produce dynamic effect . . Some of which I do not often use class, first down, write a program with this kind of thing more than a few times on the familiar.
Then directly written into the xml inside when in use on the line:
<com.demo.alldemos.diyviews.MyTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
over…