簡體   English   中英

在Rect上使用圖像和文本繪制畫布

[英]Draw canvas on Rect with image and text

我試圖使用Rect創建一個button 我已經成功創建了此圖像,但是我的圖像和文本未正確居中。 我想設置在精確的中心,但無法實現。 我需要由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);
}

預期產量

我的輸出(不完全在中心,圖像和文本之間也沒有空格

在drawView中嘗試此操作(而不是最后兩行):

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

您需要以圖標+空格+文本為中心的組合,而不僅僅是圖標。 現在,圖標完美地位於中間,而由於其高度僅為圖標的一半,因此其正下方。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM