Draw canvas on Rect with image and text

本小妞迷上赌 提交于 2019-12-23 06:09:17

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/46665278/draw-canvas-on-rect-with-image-and-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!