"Android Code Snippet"
Handy method to receive text as bitmap, so later on someone can draw that into another view.
public Bitmap getTextAsBitmap(Context gContext,
String gText,int mColor,boolean boldenabled,boolean italicenabled,Typeface myFontType) {
Resources resources = gContext.getResources();
float scale = resources.getDisplayMetrics().density;
// new antialised Paint
Paint paint = new Paint();
if(boldenabled && italicenabled){
paint.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD_ITALIC));
paint.setTextSkewX(-0.25f);
}else if(boldenabled){
paint.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
paint.setTextSkewX(0.0f);
}else if(italicenabled){
paint.setTypeface(Typeface.defaultFromStyle(Typeface.ITALIC));
paint.setTextSkewX(-0.25f);
}else{
paint.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
paint.setTextSkewX(0.0f);
}
// text size in pixels
paint.setTextSize((int) (textSize*3 * scale));
if (myFontType != null) {
paint.setTypeface(myFontType);
}
paint.setColor(mColor);
// draw text to the Canvas center
Rect bounds = new Rect();
paint.getTextBounds(gText, 0, gText.length(), bounds);
Bitmap bitmap = Bitmap.createBitmap(bounds.width(), bounds.height(), android.graphics.Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
int x = (bitmap.getWidth() - bounds.width())/2;
int y = (bitmap.getHeight())/2;
canvas.drawText(gText, x * scale, y * scale, paint);
return bitmap;
}
Handy method to receive text as bitmap, so later on someone can draw that into another view.
public Bitmap getTextAsBitmap(Context gContext,
String gText,int mColor,boolean boldenabled,boolean italicenabled,Typeface myFontType) {
Resources resources = gContext.getResources();
float scale = resources.getDisplayMetrics().density;
// new antialised Paint
Paint paint = new Paint();
if(boldenabled && italicenabled){
paint.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD_ITALIC));
paint.setTextSkewX(-0.25f);
}else if(boldenabled){
paint.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
paint.setTextSkewX(0.0f);
}else if(italicenabled){
paint.setTypeface(Typeface.defaultFromStyle(Typeface.ITALIC));
paint.setTextSkewX(-0.25f);
}else{
paint.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
paint.setTextSkewX(0.0f);
}
// text size in pixels
paint.setTextSize((int) (textSize*3 * scale));
if (myFontType != null) {
paint.setTypeface(myFontType);
}
paint.setColor(mColor);
// draw text to the Canvas center
Rect bounds = new Rect();
paint.getTextBounds(gText, 0, gText.length(), bounds);
Bitmap bitmap = Bitmap.createBitmap(bounds.width(), bounds.height(), android.graphics.Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
int x = (bitmap.getWidth() - bounds.width())/2;
int y = (bitmap.getHeight())/2;
canvas.drawText(gText, x * scale, y * scale, paint);
return bitmap;
}
No comments:
Post a Comment