android 字符串 转换成Bitmap 设置文本的字体: 宋体,隶书啥的,获取字体的 行高, 文字生成图片

Android 文字绘制到Bitmap上 OpenGL ES中似乎不能输出文本.
将文本写到Bitmap上,再作为贴图,则可实现文字输出. 

文字绘制到Bitmap上的方法为:
 String mstrTitle = "文字渲染到Bitmap!"; 
 Bitmap bmp = Bitmap.createBitmap(256,256, Bitmap.Config.ARGB_8888); //图象大小要根据文字大小算下,以和文本长度对应 
 Canvas canvasTemp = new Canvas(bmp); canvasTemp.drawColor(Color.WHITE); 
 Paint p = new Paint(); 
 String familyName ="宋体";
 Typeface font = Typeface.create(familyName,Typeface.BOLD); 
 p.setColor(Color.RED); 
 p.setTypeface(font); 
 p.setTextSize(22); 
 canvasTemp.drawText(mstrTitle,0,100,p); 
 
本例图是黑底红字我们可以用Bitmap.getPixel,和setPixel或getPixels,setPixels,取得点的颜色,根据是否有点,将Alpha通道清空,获得透明的字. 
模拟器上显示中文无问题,不知道手机对中文的支持如何. 

下面是我自己使用的方法,发现这个Bitmap转换成ImageSpan,比较精确的高度

/**
* 将文字 生成 文字图片 生成显示编码的Bitmap,目前这个方法是可用的

* @param contents
* @param context
* @return
*/
public static Bitmap creatCodeBitmap(String contents ,Context context) {
float scale=context.getResources().getDisplayMetrics().scaledDensity;

TextView tv = new TextView(context);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(layoutParams);
tv.setText(contents);
tv.setTextSize(scale*12);
tv.setGravity(Gravity.CENTER_HORIZONTAL);
tv.setDrawingCacheEnabled(true);
tv.setTextColor(Color.BLACK);
tv.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
tv.layout(0, 0, tv.getMeasuredWidth(), tv.getMeasuredHeight());


tv.setBackgroundColor(Color.GREEN);

tv.buildDrawingCache();
Bitmap bitmapCode = tv.getDrawingCache();
return bitmapCode;
}




获取 android 文本的一行的行高

http://apps.hi.baidu.com/share/detail/21391920
 


网络中好多资料介绍获取字体高度的方法如下:
 


Java代码
 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;  
 }  
 



个人更倾向于以下方式获取字体实际高度: 
 


Java代码
 Math.ceil(fm.descent - fm.ascent)  
 
width=p.measureText(data);


通过实际的截图对文字高度的确定,后者更准确一些。 
 
有了字体高度信息,就可以添加行与行之间的空隙,调整行高。 
 个人实现方式如下: 
 


Java代码
 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);  
 



实践验证这种方式对多种分辨率的屏幕的适应性较强。


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值