最近在使用textview跑马灯的效果时发现,文字在滚动的时候,Textview的边缘部分文字会有淡化的效果,最终跟踪源码发现是view中实现的该效果,经过分析实现了这样的功能,代码如下:
publicclass TextViewExextends TextView {
private Paintpaint;
private Matrixmatrix;
private LinearGradientshader;
public TextViewEx(Context context, AttributeSet attrs,int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
init();
}
public TextViewEx(Context context, AttributeSet attrs) {
this(context, attrs, 0);
// TODO Auto-generated constructor stub
}
public TextViewEx(Context context) {
this(context,null);
// TODO Auto-generated constructor stub
}
privatevoid init() {
paint =new Paint();
matrix =new Matrix();
// use use a height of 1, and thenwack the matrix each time we
// actually use it.
shader =new LinearGradient(0, 0, 0, 1, 0xFF000000, 0,
Shader.TileMode.CLAMP);
paint.setShader(shader);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
}
@Override
publicvoid draw(Canvas canvas) {
//这里是view draw中的部分代码,复制出来的
canvas.saveLayer(0, 0, 0 + 100, 50,null, 4);
canvas.saveLayer(1920 - 100, 0, 1920, 50,null, 4);
super.draw(canvas);
matrix.setScale(1, 100 * 1);
matrix.postRotate(-90);
matrix.postTranslate(0, 0);
shader.setLocalMatrix(matrix);
canvas.drawRect(0, 0, 0 + 100, 50,paint);
// right
matrix.setScale(1, 100 * 1);
matrix.postRotate(90);
matrix.postTranslate(1920, 0);
shader.setLocalMatrix(matrix);
canvas.drawRect(1920 - 100, 0, 1920, 50,paint);
}
@Override
protectedvoid onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
}
}
这样这个view就有了边缘淡化的效果了。使用如下:
<com.example.lineagdemo.TextViewEx
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="none"
android:singleLine="true"
android:textColor="#00ff00"
android:text="你好啊亲你好啊亲你好啊亲你好啊亲你好啊亲你好啊亲你好啊亲你好啊亲你好啊亲你好啊亲你好啊亲!!!你好啊亲你好啊亲你好啊亲你好啊亲你好啊亲你好啊亲你好啊亲你好啊亲你好啊亲你好啊亲你好啊亲你好啊亲你好啊亲你好啊亲"/>
效果图如下: