EditText画行,每行画分割线。
其中一些值的设置与当前手机的分辨率,屏幕密度,字体大小都有关系,下面是我自己找出的一组比较合理的值
WVGA:480*800,屏幕密度240:
当字体为22sp时,baseline=35px=basicline, lineHight=39px=linedistance;
当字体为21sp时,baseline=34px=basicline, lineHight=38px=linedistance;
当字体为20sp时,baseline=32px=basicline, lineHight=35px=linedistance;
当字体为19sp时,baseline=31px=basicline, lineHight=34px=linedistance;
当字体为18sp时,baseline=29px=basicline, lineHight=31px=linedistance;
因为如果使用px为单位,在其他不同分辨率下,效果不一样,这里有换算公式,但是不同分辨率还是不同的。
本人觉得使用px简单一些,麻烦的是不同分辨率还需要修改,这个还没想到解决办法,有高手知道的请分享一下,先谢谢了!
换算公式为:
pixs =dips * (densityDpi/160).
dips=(pixs*160)/densityDpi
例如分辨率为480*800,密度为240的设备,方法如下:
DisplayMetrics dm =getResources().getDisplayMetrics();
dm.densityDpi=240
dm.widthPixels=480
dm.heightPixels=800
以下是我的程序代码:
1 <view 2 class="com.zjq.textline.EditView" 3 android:id="@+id/et_content" 4 android:layout_width="fill_parent" 5 android:layout_height="wrap_content" 6 android:layout_marginTop="30dip" 7 style="?android:attr/textViewStyle" 8 android:background="@android:color/transparent" 9 android:padding="5dip" 10 android:scrollbars="vertical" 11 android:fadingEdge="vertical" 12 android:gravity="top|left" 13 14 android:editable="true" 15 android:cursorVisible="true" 16 android:textColor="@color/black" 17 android:textSize="22sp" 18 android:capitalize="sentences" 19 android:imeOptions="actionDone" 20 />
Java 代码
1 @Override 2 protected void onDraw(Canvas canvas) { 3 int count = getLineCount(); // method entends from TextView. 4 Rect r = mRect; 5 Paint paint = mPaint; 6 7 //第一次画第一条线。以后每次输入,换行时仍然检测,继续画线 8 for (int i = 0; i < count; i++) { 9 int baseline = getLineBounds(i, r); 10 canvas.drawLine(0, baseline + 1, r.right, baseline + 1, paint); 11 //get baseline 12 Log.i(TAG, "baseline------->"+baseline+" "); 13 } 14 //根据判定条件,画出13条线 15 if(count < linecount){ 16 for (int j = count; j < linecount; j++) { 17 float baseline = basicline + j*linedistance; 18 canvas.drawLine(0, baseline + 1, r.right, baseline + 1, paint); 19 //get lineHeight 20 int len = getLineHeight(); 21 // Log.i(TAG, len +" "); 22 } 23 } 24 25 super.onDraw(canvas); 26 }
不同分辨率,设置不同的baseline,linedistance
1 if((mWidthPixels == 480 && (mHeightPixels == 800 || mHeightPixels == 854))|| 2 ((mWidthPixels == 800 || mWidthPixels == 854) && mHeightPixels == 480)){ 3 linecount = 16; 4 basicline = 43; 5 linedistance = 39; 6 Log.i(TAG, "480X800-------------");// basicline = 43;linedistance = 39;这组值合适 7 }else if((mWidthPixels == 320 && mHeightPixels == 480)||(mWidthPixels == 480 && mHeightPixels == 320)){ 8 linecount = 14; 9 basicline = 29; 10 linedistance = 25; 11 Log.i(TAG, "320X480--------------"); 12 }else if((mWidthPixels == 320 && mHeightPixels == 240)||(mWidthPixels == 240 && mHeightPixels == 320)){ 13 linecount = 16; 14 basicline = 18; 15 linedistance = 20; 16 Log.i(TAG, "320X240--------------"); 17 } 18 Log.i(TAG, mWidthPixels +" X " +mHeightPixels + ": basicline = " + basicline +",linedistance = " + linedistance ); 19 setLines(linecount);