【问题标题】:Android/Java - Draw text at the bottom of a bitmapAndroid/Java - 在位图底部绘制文本
【发布时间】:2018-08-24 05:23:17
【问题描述】:

我试图在位图底部放置白色文本。此外,我想将文本水平居中,但这是可选的。

val canvas = Canvas(bitmap)
val paint = Paint()
paint.color = Color.WHITE
paint.textSize = 50f
canvas.drawText("Meme Text", 30f, bitmap.height - 50f, paint)

我假设因为我将文本的 y 值设置为 bitmap.height - 50,所以文本将与位图的底部对齐(因为 textSize50f

但是,实际上,文本不会出现在图像的底部。我该如何解决这个问题?

下面是对应的Java代码:

Bitmap bitmap = ... // Load your bitmap here
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint(); 
paint.setColor(Color.BLACK); 
paint.setTextSize(10); 
canvas.drawText("Some Text here", x, y, paint);

更新:我试过了,但帮助不大。

    val metrics = context.resources.displayMetrics

    canvas.drawText("Meme Text", 30f,canvas.height
            - paint.textSize/metrics.density, paint)

【问题讨论】:

  • paint.setTextSize(10f) ,这里 10f 不代表高度。根据textSize计算高度,需要使用Paint.getTextBounds()

标签: java android bitmap kotlin android-bitmap


【解决方案1】:

结果证明解决方案非常简单。改变

canvas.drawText("Meme Text", 30f, bitmap.height - 50f, paint) canvas.drawText("Meme Text", 30f, bitmap.height, paint) .

似乎canvas.drawText 绘制的文本底部与 y 坐标对齐。

【讨论】:

    【解决方案2】:
        Canvas canvas = new Canvas(bitmap);
    // new antialised Paint
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    // text color - #3D3D3D
    paint.setColor(Color.rgb(110,110, 110));
    // text size in pixels
    paint.setTextSize((int) (12 * scale));
    // text shadow
    paint.setShadowLayer(1f, 0f, 1f, Color.DKGRAY);
    
    // draw text to the Canvas center
    Rect bounds = new Rect();
    paint.getTextBounds(mText, 0, mText.length(), bounds);
    int x = (bitmap.getWidth() - bounds.width())/6;
    int y = (bitmap.getHeight() + bounds.height())/5;
    
    canvas.drawText(mText, x * scale, y * scale, paint);
    

    使用此代码希望它能满足您的要求

    【讨论】:

    • 变量scale是什么意思/我应该如何设置它?
    • 资源资源 = mContext.getResources(); float scale = resources.getDisplayMetrics().density;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 2020-09-19
    • 1970-01-01
    • 2013-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多