3

I want to draw a rectangle as a transparent canvas on my given text as following image: enter image description here

I am using following code to draw the transparent rectangle but not able to understand the coordinates position. I tried a lot of time but it's not working.

canvas.drawRect(left,top,right,bottom,paint);

Here is my code:

Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.FILL);
paint.setTextSize(40);
paint.setShadowLayer(2.0f, 1.0f, 1.0f, Color.BLACK);
paint.setAlpha(255);
rectPaint.setAlpha(100);
canvas.drawText("$250", 20, 400, paint);
canvas.drawBitmap(bitmapImage, 490, 55, null);
canvas.drawRect(0, 100, 300, 400, rectPaint);

What would be the value of rest of the coordinates in drawRect method to align it as given coordinates of text. Right now I am using

canvas.drawRect(0, ? , ? , ?, rectPaint);   
Amit Pal
  • 10,604
  • 26
  • 80
  • 160
  • drawRect(float left, float top, float right, float bottom, Paint paint) -- best to make the rectangle not transparent so at least you can see it on screen and play around with position to understand it better – Tasos Sep 21 '15 at 11:32
  • I can see the rectangle on my screen but not able to set it on the correct position. I have already played with it for almost one hour :( – Amit Pal Sep 21 '15 at 11:33
  • @Tasos can you please look at the Eidt-1 section – Amit Pal Sep 21 '15 at 11:43
  • here is some help to understand how position works -- http://stackoverflow.com/questions/19464962/understanding-how-actually-drawrect-or-drawing-coordinates-work-in-android – Tasos Sep 21 '15 at 11:49
  • Actually I followed it but location is not changing as per suggestion. I don't know why. BTW I tried your coordinates and it gave me this: http://i.imgur.com/Uwhbb2U.png – Amit Pal Sep 21 '15 at 11:55
  • BTW canvas.drawRect(0, 350, 140, 420, rectPaint); works for me. I will Add my answer with better understanding. – Amit Pal Sep 21 '15 at 12:21
  • canvas position also acts as the size by the sounds of it. you can also do a drawable rectangle shape -- http://stackoverflow.com/questions/10124919/can-i-draw-rectangle-in-xml – Tasos Sep 21 '15 at 20:16
  • Yes, But it was not possible in my situation because I am using Picasso transformation to add new Image – Amit Pal Sep 21 '15 at 20:23

1 Answers1

0

You could use the Paint.getTextBounds() method for this.

getTextBounds(String text, int start, int end, Rect bounds)

Return in bounds (allocated by the caller) the smallest rectangle that encloses all of the characters, with an implied origin at (0,0).

This will give you the Rect that you want, you then need to offset this Rect with the coordinates that you supplied with the drawText call.

Henry
  • 17,490
  • 7
  • 63
  • 98