Skip to content

Instantly share code, notes, and snippets.

@lilac
Last active August 29, 2015 14:26
Show Gist options
  • Save lilac/0377b7f5cb18f536e62f to your computer and use it in GitHub Desktop.
Save lilac/0377b7f5cb18f536e62f to your computer and use it in GitHub Desktop.
Bitmap bitmap = Bitmap.createBitmap(pageWidth, pageHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
// inflate a view
View view = LayoutInflater.from(context).inflate(R.layout.view, null);
int marginLeft = 100;
int marginTop = 100;
Rect bound = new Rect(marginLeft, marginTop, pageWidth - marginLeft, pageHeight - marginTop);
//Measure the view at the exact dimensions (otherwise the text won't center correctly)
int widthSpec = View.MeasureSpec.makeMeasureSpec(bound.width(), View.MeasureSpec.EXACTLY);
int heightSpec = View.MeasureSpec.makeMeasureSpec(bound.height(), View.MeasureSpec.EXACTLY);
view.measure(widthSpec, heightSpec);
view.layout(0, 0, bound.width(), bound.height());
// translate position
canvas.save();
canvas.translate(marginLeft, marginTop);
view.draw(canvas);
canvas.restore();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment