您的位置:首页 > 其它

自定义View之自定义文字闪动效果

2017-06-03 00:38 344 查看
自定义View之自定义文字闪动效果,代码是学习《Android群英会》中的例子略有改动

效果如图



直接上自定义控件的代码

package com.cheng.cc.customcontrols.views;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.widget.TextView;

/**
* @author Created by cc on 17/6/2.
* @fileName LightningTextView
* @githublink https://github.com/cc0819 * @csdnlink http://blog.csdn.net/qq_25404567 */

public class LightningTextView extends TextView {

private int mViewWidth;
private int mTranslate;
private Paint mPaint;
private LinearGradient mLinearGradient;
private Matrix mGradientMatrix;

public LightningTextView(Context context) {
super(context);
}

public LightningTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}

public LightningTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}

@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,Color.YELLOW,Color.RED},
null, Shader.TileMode.CLAMP);//设置线性渲染的颜色
// CLAMP表示重复最后一种颜色直到该View结束的地方
// REPEAT表示着色器在水平或者垂直方向上对控件进行重复着色
// MIRROR模式会在水平方向或者垂直方向上以镜像的方式进行渲染
mPaint.setShader(mLinearGradient);
mGradientMatrix = new Matrix();

}

}
}

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mGradientMatrix != null){
mTranslate += mViewWidth / 5 ;//已控件宽度的五分之一移动渲染的矩阵达到闪动效果
if (mTranslate > 2*mViewWidth){
mTranslate = -mViewWidth;
}
mGradientMatrix.setTranslate(mTranslate,0);
mLinearGradient.setLocalMatrix(mGradientMatrix);
postInvalidateDelayed(80);

}
}

}


布局中引用

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context="com.cheng.cc.customcontrols.activity.TextLightning_Activity">

<com.cheng.cc.customcontrols.views.LightningTextView
android:id="@+id/lightning"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"/>
</LinearLayout>


文字内容和大小是在代码中动态设置的

lightning.setText("LIGHTNING TEXTVIEW");
lightning.setTextSize(50);


github下载地址:https://github.com/cc0819/CustomControls
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: