Return to Snippet

Revision: 65987
at February 20, 2014 22:13 by cbruegg


Initial Code
public static Bitmap drawText(String text, int textWidth, int textSize) {
		// Get text dimensions
		TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG
				| Paint.LINEAR_TEXT_FLAG);
		textPaint.setStyle(Paint.Style.FILL);
		textPaint.setColor(Color.BLACK);
		textPaint.setTextSize(textSize);
		StaticLayout mTextLayout = new StaticLayout(text, textPaint,
				textWidth, Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
		
		// Create bitmap and canvas to draw to
		Bitmap b = Bitmap.createBitmap(textWidth, mTextLayout.getHeight(), Config.RGB_565);
		Canvas c = new Canvas(b);
		
		// Draw background
		Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG
				| Paint.LINEAR_TEXT_FLAG);
		paint.setStyle(Paint.Style.FILL);
		paint.setColor(Color.WHITE);
		c.drawPaint(paint);
		
		// Draw text
		c.save();
		c.translate(0, 0);
		mTextLayout.draw(c);
		c.restore();
		
		return b;
	}

Initial URL


Initial Description
This method draws a specified string to a Bitmap with the desired text width and text size.

Initial Title
Android: Draw text to dynamically sized bitmap

Initial Tags
image, layout

Initial Language
Java