I've trying to create a button
using Rect
. I've created this successfully but my image and text is not properly on center. I want set in exact center but can't achieve. I need to do this by Rect
. please guide me, any help would be appreciated. Thanks
Here is my code snippet
RectF rightButton = new RectF(itemView.getRight() -
buttonWidthWithoutPadding, itemView.getTop(), itemView.getRight(), itemView.getBottom());
p.setColor(Color.parseColor("#F44336"));
c.drawRoundRect(rightButton, corners, corners, p);
drawView("DELETE", c, rightButton, p);
//draw view method
private void drawView(String text, Canvas c, RectF button, Paint p) {
float textSize = 20;
p.setColor(Color.WHITE);
p.setAntiAlias(true);
p.setTextSize(textSize);
float textWidth = p.measureText(text);
Bitmap bmp = drawableToBitmap(ContextCompat.getDrawable(mContext, R.drawable.delete_white_24dp));
c.drawBitmap(bmp, button.centerX() - (bmp.getWidth() / 2), button.centerY() - (bmp.getHeight()/2), null);
c.drawText(text, button.centerX() - (textWidth / 2), button.centerY() + bmp.getHeight(), p);
}
Expected output
My output (Not exactly in center also no space between image and text
Try this in drawView (instead of the last 2 lines):
float spaceHeight = 10; // change this to whatever looks good to you
Rect bounds = new Rect();
p.getTextBounds(text, 0, text.length(), bounds);
float combinedHeight = bmp.getHeight() + spaceHeight + bounds.height();
c.drawBitmap(bmp, button.centerX() - (bmp.getWidth() / 2), button.centerY() - (combinedHeight / 2), null);
c.drawText(text, button.centerX() - (textWidth / 2), button.centerY() + (combinedHeight / 2), p);
You want the combination of icon+space+text centered, not just the icon. Right now the icon is perfectly in the middle and the text, due to being half as high as the icon, is exactly below it.