Search code examples
androidscaleandroid-canvas

How to scale text on a bitmap?


i'm trying to draw text on a bitmap. When text is short everything is working fine, but when text is long it just paints it out of screen.

How can i fix it? This is my releavent code :

      Canvas canvas = new Canvas(bitmap);
      // new antialised Paint
      Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
      // text color - #3D3D3D
      paint.setColor(Color.WHITE);
      // text size in pixels
      paint.setTextSize((int) (108 * scale));
      // text shadow
      paint.setShadowLayer(1f, 0f, 1f, Color.BLACK);


      // draw text to the Canvas center
      Rect bounds = new Rect();
      paint.getTextBounds(gText, 0, gText.length(), bounds);
      int x = (bitmap.getWidth() - bounds.width())/2;
      int y = (bitmap.getHeight() + bounds.height())/2;

      canvas.drawText(gText, x * scale, y * scale, paint);

EDIT: In 2nd thought, it could be a better idea to find out i the text will be longer then screen, then if it will, split the string and draw the 2nd half in a new line. Am i right?


Solution

  • paint.measureText

    http://developer.android.com/reference/android/graphics/Paint.html#measureText(char[], int, int)

    Compare with your views width minus the x offset of the start of the text. Split the text as needed. Voila! Good luck