應用: 在做txt閱讀器或者顯示英文字元時,要判斷一個單詞是否被斷開啦。如下簡單代碼能夠自動識別單詞,並且繪畫在螢幕上。 貌似目前很多閱讀器,比如百度文庫和百閱,都沒有對單詞處理。看著相當蛋疼。不過你處理來單詞後,後面將有很多內容 需要處理。這就是百度文庫(android用戶端)或者百閱閱讀器捨棄對文文書處理的原因。package com.docintes.canvas;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.Path;import android.graphics.Rect;import android.util.AttributeSet;import android.util.Log;import android.view.View;public class MyTextView extends View {private Paint mPaint;private static String mString = "Whatonship of deep love, about love? In a relationship of deep love,In a relationship of deep love, all the sharing that we discussed above are taken for granted. But love transcends all this. During love, we are attached with a particular person, while in friendship, one may have many friends. A loving relationship makes one so much attached to the other, that one gets pained if his/her beloved is hurt! Love also involves a physical element. Friendship does not have that. This is a vital difference. Nature gives us love so that the specie can go forward. Nature does not give us friendship.";private Path mPath;private int textSize = 24;private static int xAdd = 0;private float strheight = 0;private float strwidth = 0;final int strLength=mString.length();public MyTextView(Context context) {super(context);}public MyTextView(Context context, AttributeSet attr) {super(context, attr);}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);mPaint = new Paint();mPath = new Path();mPaint.setColor(Color.argb(255, 255, 255, 255)); // mPaint設定畫布顏色canvas.drawRect(0, 0, getWidth(), getHeight(), mPaint); // 畫一個長方形用於顯示歌詞mPaint.setColor(Color.argb(255, 0, 0, 0));mPath.moveTo(0, 0);mPath.lineTo(getWidth(), 0);Rect rec = new Rect();mPaint.setTextSize(textSize);mPaint.setAntiAlias(true);mPaint.getTextBounds(mString, 0, mString.length(), rec);strheight = rec.height();strwidth = mPaint.measureText(mString);while (strwidth >= getWidth()) { strwidth = drawTheText(canvas, mString,mPath, mPaint);}//canvas.drawTextOnPath(mString, mPath, xAdd, height, mPaint);}static float height = 0;float drawTheText(Canvas canvas, String str, Path mPath,Paint mPaint) {int theLinePoint = 0;StringBuffer tempString =new StringBuffer();float tempwidth = 0;do {tempString.append(str.charAt(theLinePoint));tempwidth = mPaint.measureText(tempString.toString());theLinePoint ++;}while((tempwidth +mPaint.measureText("A"))<= getWidth()&&theLinePoint<str.length());height += (strheight + 10);if(str.charAt(theLinePoint-1)!=' '&&theLinePoint<str.length()){theLinePoint--;do{if(str.charAt(theLinePoint)!=' ')theLinePoint--;else {break;}}while(theLinePoint>1);canvas.drawTextOnPath(str.substring(0,theLinePoint), mPath, xAdd, height, mPaint);}else {canvas.drawTextOnPath(str.substring(0,theLinePoint), mPath, xAdd, height, mPaint);}mString=str.substring(theLinePoint).trim();Log.i("............wokou",mString);return mPaint.measureText(str);}}
:
( 顯示的字是一個單詞,注意換行的地方。)