Search code examples
javaandroidpaintbitmapfactoryoval

How to draw oval shape (rectangle with round corners) as text background using Paint and Convas in Android java


I am trying to add an oval background to my text according to its size using Paint. There are a few problems in my code.

  1. I want to draw rectangle with round corners instead of the circles.
  2. Its size does not changes according to text length.

Here is my code so far:

Bitmap.Config conf = Bitmap.Config.ARGB_8888;
Bitmap bmp = Bitmap.createBitmap(500, 280, conf);
Canvas canvas1 = new Canvas(bmp);
                        
Paint color = new Paint();
color.setTextSize(30);
color.setColor(Color.BLACK);

Paint clr2=new Paint();
clr2.setColor(Color.WHITE);
canvas1.translate(200/2f,100/2f);
canvas1.drawCircle(50,0, 50, clr2);
canvas1.drawText(new Random().nextInt()+" $", 0, 0, color);`

Current results:

enter image description here

Expected results:

enter image description here


Solution

  • Final Result after making changes to @Nguyễn's Answer:

    //Creating text of random length
    final int min = 1;
    final int max = 999999;
    final String text = new Random().nextInt((max - min) + 1) + min +" USD";
    
    //Creating bitmap width according to text length
    Bitmap.Config conf = Bitmap.Config.ARGB_8888;
    Bitmap bmp = Bitmap.createBitmap(text.length()*20, 50, conf);
    
    //Setting up Text properties
    Paint color = new Paint();
    Typeface typeface = Typeface.DEFAULT_BOLD;
    color.setTypeface(typeface);
    color.setTextSize(30);
    color.setColor(Color.BLACK);
    
    //Setting up Rectangle
    Rect rectText = new Rect();
    Paint paint = new Paint();
    paint.setTextSize(32);
    paint.setColor(Color.WHITE);
    
    //Creating Convas object for the bitmap
    Canvas canvas = new Canvas(bmp);
    
    //Drawing rectangle with round corners and it width according to the text length with some extra padding
    paint.getTextBounds(text, 0, text.length(), rectText);
    canvas.drawRoundRect(rectText.left,10,rectText.right+10,50,10,40,paint);
    
    //Drawing text
    canvas.drawText(text, 10, 40, color);
    

    Here is the output:

    enter image description here