2017-10-10 187 views
-1

我试图使用Rect创建button。我已经成功创建了这个图片,但是我的图片和文字不在中心。我想设置在确切的中心,但无法实现。我需要通过Rect来做到这一点。请指导我,任何帮助将不胜感激。由于在Rect上绘制画布图像和文字

这里是我的代码片段

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); 
} 

预计输出

我的输出(不完全是在中心还图像和文本之间没有空格

回答

1

在drawView函数试试这个(而不是最后2行):

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); 

你想中心图标+空格+文字的组合,而不仅仅是图标。现在这个图标完全在中间,由于图标的一半高度,图标正好在它的下面。

+0

感谢它的工作 –