第一步,把文字转成图片。
//文本文字转Bitmap
/*
textStr需要转变成图片的文字
textFontSize文字大小
width转变成图片的宽
height转变成图片的高
说明:宽高可以不指定让图片随文字的变化而变化
*/
public static Bitmap creatTextBitmap(Context context,String textStr, int textFontSize, int width, int height,)
{
TextView tv = new TextView(context);
tv.setTextSize(textFontSize);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(layoutParams);
tv.setText(textStr);
tv.setHeight(height);//设置高
tv.setWidth(width);//设置宽
tv.setGravity(Gravity.CENTER_HORIZONTAL);
tv.setDrawingCacheEnabled(true);
tv.setBackgroundColor(Color.WHITE);//设置文字的背景颜色
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.buildDrawingCache();
Bitmap bitmapCode = tv.getDrawingCache();
return bitmapCode;
}
第二步,把文字转成的图片绘制到图片上。
/*
* 将两个Bitmap合并成一个
first:第一个Bitmap,相当于背景底图
second:第二个Bitmap
fromPoint:第二个Bitmap开始绘制的起始位置(相对于第一个Bitmap)
*/
protected static Bitmap mixtureBitmap(Bitmap first, Bitmap second,PointF fromPoint)
{
if (first == null || second == null || fromPoint == null)
{
return null;
}
int marginW = 0;
Bitmap newBitmap = Bitmap.createBitmap(first.getWidth() + marginW+ marginW, first.getHeight() + second.getHeight(), Config.ARGB_4444);
Canvas cv = new Canvas(newBitmap);
cv.drawBitmap(first, marginW, 0, null);
cv.drawBitmap(second, fromPoint.x, fromPoint.y, null);
cv.save(Canvas.ALL_SAVE_FLAG);
cv.restore();
return newBitmap;
}