Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // int gravity: see android.view.Gravity, like Gravity.LEFT, Gravity.BOTTOM, etc
- public Bitmap addText(Bitmap in, String text, int gravity){
- Bitmap out = in.copy(Bitmap.Config.ARGB_8888,true);
- Canvas canvas = new Canvas(out);
- Paint paint = new Paint();
- paint.setColor(Color.WHITE);
- paint.setStyle(Paint.Style.FILL);
- Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
- textPaint.setColor(Color.BLACK);
- // textPaint.setTextSize(128);
- textPaint.setTextAlign(Paint.Align.LEFT);
- Rect inBounds = new Rect();
- textPaint.getTextBounds(text, 0, text.length(), inBounds);
- float scale = out.getWidth() * 0.35f / inBounds.width();
- Rect container = new Rect(0, 0, out.getWidth(), out.getHeight());
- Rect outBounds = new Rect();
- int w = (int) (inBounds.width() * scale);
- int h = (int) (inBounds.height() * scale);
- Gravity.apply(gravity, w, h, container, outBounds);
- canvas.drawRect(outBounds, paint);
- Matrix matrix = new Matrix();
- RectF src = new RectF(inBounds);
- RectF dst = new RectF(outBounds);
- matrix.setRectToRect(src, dst, Matrix.ScaleToFit.CENTER);
- canvas.concat(matrix);
- canvas.drawText(text, 0, 0, textPaint);
- return out;
- }
Add Comment
Please, Sign In to add comment