@cxm-2016
2017-01-19T11:14:52.000000Z
字数 2273
阅读 2954
Android
版本:1
在Android SDK中使用Typeface类来定义字体,可以通过常用字体类型名称进行设置,如设置默认黑体:
Paint mp = new paint();mp.setTypeface(Typeface.DEFAULT_BOLD)
常用的字体类型名称还有:
除了字体类型设置之外,还可以为字体类型设置字体风格,如设置粗体:
Paint mp = new Paint();Typeface font = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD);p.setTypeface( font );
常用的字体风格名称还有:
但是有时上面那些设置在绘图过程中是不起作用的,所以还有如下设置方式:
Paint mp = new Paint();mp.setFakeBoldText(true); //true为粗体,false为非粗体mp.setTextSkewX(-0.5f); //float类型参数,负数表示右斜,整数左斜mp.setUnderlineText(true); //true为下划线,false为非下划线mp.setStrikeThruText(true); //true为删除线,false为非删除线
Paint常用的方法还有:
mp.setTextSize(); //设置字体大小,int型,如12mp.setStrokeWidth(w);//设置线宽,float型,如2.5f,默认绘文本无需设置,但假如设置了,再绘制文本的时候一定要恢复到0
说明:对于中文粗体的设置,只能通过setFakeBoldText(true)来实现,尽管效果看起来不是很实在(字体中空效果)。实际发现,最后绘制的效果与手机硬件也有些关系,比如前面的绘图测试程序,在HTC里面黑体中文一行没显示(英文和数字是正常的),而斜体一行显示了,只是没有斜体效果。魅族M9表现的很给力,可能是M9定制的Android系统里面字体库比较丰富吧!
public void onDraw(Canvas canvas){super.onDraw(canvas);Paint p = new Paint();String familyName = “宋体”;Typeface font = Typeface.create(familyName,Typeface.BOLD);p.setColor(Color.RED);p.setTypeface(font);p.setTextSize(22);canvas.drawText(mstrTitle,0,100,p);}
public int getFontHeight(float fontSize) {Paint paint = new Paint();paint.setTextSize(fontSize);FontMetrics fm = paint.getFontMetrics();return (int) Math.ceil(fm.descent - fm.top) + 2;}
个人更倾向于以下方式获取字体实际高度:
Math.ceil(fm.descent - fm.ascent)
通过实际的截图对文字高度的确定,后者更准确一些。
有了字体高度信息,就可以添加行与行之间的空隙,调整行高。
paint.setTextSize(fFontWidth);FontMetrics fm = paint.getFontMetrics();fFontHeight = (float)Math.ceil(fm.descent - fm.ascent);if(fFontHeight > fLineHeight){fMulValue = fLineHeight / fFontHeight;fAddValue = -1;}else{fMulValue = 1;fAddValue = fLineHeight - fFontHeight;}textViewLeft.setTextSize(fFontWidth);textViewLeft.setLineSpacing(fAddValue, fMulValue);
实践验证这种方式对多种分辨率的屏幕的适应性较强。
Typeface.createFromAsset(getContext().getAssets(),"fonts/samplefont.ttf");paint.setFlags(Paint.ANTI_ALIAS_FLAG) //消除锯齿paint.measureText(String s) //取得字符串宽度
Canvas 作为绘制文本时,使用FontMetrics对象,计算位置的坐标。
