Android实现字幕滚动,不使用内置的属性,而是重新定义一个类继承自AppCompatTextView来实现,可以控制文字滚动速度且让其匀速滚动,首先定义一个方法
得到屏幕宽度和文本长度
public void scrollTextView(WindowManager windowManager, String text) {
// 获取画笔paint
paint = this.getPaint();
//paint.setColor(Color.BLACK);
//使用抗锯齿效果,使文本更加平滑
paint.setSubpixelText(true);
paint.setAntiAlias(true);
//设置文字大小和颜色
paint.setTextSize(50);
this.setTextColor(Color.BLACK);
// 得到文字
this.text = text;
textLength = paint.measureText(text);// 获得当前文本字符串长度
viewWidth = this.getWidth();// 获取view的宽度;
if (viewWidth == 0) {
if (windowManager != null) {
// 获取当前屏幕的属性
Display display = windowManager.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
viewWidth = size.x;// 获取屏幕宽度
}
}
xPos = textLength;
currentLength = viewWidth + textLength;
changeLength = viewWidth + textLength * 2;// 使文字到最左边
// 文字的大小+距顶部的距离
yPos = this.getTextSize() + this.getPaddingTop();
}
重写onDraw方法
@Override
protected void onDraw(Canvas canvas) {
/**
* 两次进入onDraw函数的时间间隔
*/
time1 =System.currentTimeMillis();
if (time2!=0){
timeDesc=time1-time2;
}
speed=getSpeed();
TIME=getTIME();
//文字从最右边开始滚动
if (isStarting) {
canvas.drawColor(Color.WHITE);
canvas.drawText(text, currentLength - xPos, yPos, paint);
//每次滚动速度
if (timeDesc!=0){
if (TIME!=0){
xPos += speed/TIME*timeDesc;//根据时间差计算滚动距离
}
else {
xPos =xPos+ 0;
}
}
else {
xPos += speed;
}
// 当文字滚动到屏幕的最左边
if (xPos >= changeLength) {//最后一个文字到达最左边时
// 把文字设置到最右边开始
xPos = currentLength - viewWidth;
}
}
time2 = time1;
super.onDraw(canvas);
}
然后在
MainActivity中实现一个定时器
,控制刷新时间
Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
// handler自带方法实现定时器
try {
handler.postDelayed(this, TIME);
marquee.invalidate();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
MainActivity
中的onCreate方法控制刷新时