【问题标题】:Draw canvas on Rect with image and text使用图像和文本在 Rect 上绘制画布
【发布时间】:2017-10-10 11:09:56
【问题描述】:

我正在尝试使用Rect 创建一个button。我已经成功创建了这个,但是我的图像和文本没有正确地居中。我想设置在精确的中心但无法实现。我需要通过Rect 执行此操作。请指导我,任何帮助将不胜感激。谢谢

这是我的代码 sn-p

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

预期输出

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

【问题讨论】:

    标签: android android-canvas


    【解决方案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);
    

    您希望图标+空格+文本的组合居中,而不仅仅是图标。现在图标完全在中间,而文本由于是图标的一半高,正好在它的下方。

    【讨论】:

    • 将 spaceHeight 添加为 float 会导致它在不同屏幕上看起来具有不同的高度,对吧?我们不应该使用 dp 吗?
    • 不确定你的意思。也许您将数值类型“float”与 html/css 属性“float”混为一谈?这个浮动绝对不是动态调整到屏幕大小或其他任何东西的东西,它被定义为 10(或您选择将其更改为的任何值),因此只会在图片和文本之间添加 10 个像素。
    • 澄清一下:RectF button.centerY() 返回一个浮点数,而 Canvas c.drawBitmap(...) 接受一个浮点数(或整数,但不是双精度数),所以最好只需将 float 用于您要在此处添加在一起的其他值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-11
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    • 2018-02-28
    • 2011-12-10
    • 2018-12-09
    相关资源
    最近更新 更多