android TextView 垂直自動滾動字幕實現 java
textview 垂直自動滾動字幕實現
前段時間,在網上搜到一個帖子,textview水平自動滾動字幕的實現,今日項目須要垂直滾動字幕。其實現原理和水品同樣。都是重寫textview的onDraw方法。
實現垂直自動滾動字幕須要2點須要注意
1.須要根據textview的寬度和字體的大小計算滾動字幕有多少行。實現這個功能,須要從新寫兩個方法:1.onMeasure,2.onDraw.由於須要獲取textview的寬度,因而須要在onMeasure方法裏面調用以下代碼。具體方法以下: android
[java] view plaincopy canvas
1. public VerticalScrollTextView extends TextView { app
2. private float step =0f; ide
3. private Paint mPaint; 字體
4. private String text; ui
5. private float width; this
6. private List<String> textList = new ArrayList<String>(); //分行保存textview的顯示信息。 .net
7. blog
8. public VerticalScrollTextView(Context context, AttributeSet attrs) {
9. super(context, attrs);
10. }
11.
12.
13. public VerticalScrollTextView(Context context) {
14. super(context);
15. }
16.
17. @Override
18. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
19. super.onMeasure(widthMeasureSpec, heightMeasureSpec);
20. width = MeasureSpec.getSize(widthMeasureSpec);
21. final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
22. if (widthMode != MeasureSpec.EXACTLY) {
23. throw new IllegalStateException("ScrollLayout only canmCurScreen run at EXACTLY mode!");
24. }
25.
26. float length = 0;
27. if(text==null|text.length()==0){
28. return ;
29. }
30.
31.
32. //下面的代碼是根據寬度和字體大小,來計算textview顯示的行數。
33.
34. textList.clear();
35.
36. StringBuilder builder = new StringBuilder();
37. for(int i=0;i<text.length();i++){
38. Log.e("textviewscroll",""+i+text.charAt(i));
39. if(length<width){
40. builder.append(text.charAt(i));
41. length += mPaint.measureText(text.substring(i, i+1));
42. if(i==text.length()-1){
43. Log.e("textviewscroll",""+i+text.charAt(i));
44. textList.add(builder.toString());
45. }
46. }else{
47. textList.add(builder.toString().substring(0,builder.toString().length()-1));
48. builder.delete(0, builder.length()-1) ;
49. length= mPaint.measureText(text.substring(i, i+1));
50. i--;
51. }
52.
53. }
54. }
55.
56.
57. //下面代碼是利用上面計算的顯示行數,將文字畫在畫布上,實時更新。
58. @Override
59. public void onDraw(Canvas canvas) {
60. if(textList.size()==0) return;
61. for (int i = 0; i < textList.size(); i++) {
62. canvas.drawText(textList.get(i), 0, this.getHeight()+(i+1)*mPaint.getTextSize()-step, getPaint());
63. }
64.
65. invalidate();
66. step = step+0.3f;
67. if (step >= this.getHeight()+textList.size()*mPaint.getTextSize()) {
68. step = 0;
69. }
70. }
71.
72. }