您的位置:首页 > 移动开发 > Android开发

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

2017-04-18 11:42 495 查看
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);

实践验证这种方式对多种分辨率的屏幕的适应性较强。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐