1

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

Waqas K
  • 144
  • 2
  • 12

2 Answers2

1
  1. If you want to draw rectangle with round corners:

    Canvas.drawRoundRect(RectF(),10f,10f,Paint())
    
  2. For each text, you can get text bound (a rect a round text), then draw this rect with round corners:

     String text = "hello";
    Rect rectText = new Rect(); 
    paint.getTextBounds(text, 0, text.length(), rectText);
    canvas.drawRoundRect(rectText.left,rectText.top,rectText.right,rectText.bottom,radius,radius,paint);
    
0

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

Waqas K
  • 144
  • 2
  • 12