【问题标题】:Draw text on bitmap in the bottom left corner在左下角的位图上绘制文本
【发布时间】:2019-07-09 10:12:28
【问题描述】:

无论位图大小如何不同,我都试图在位图上以固定位置(左下角)绘制一些文本。

以下代码有效,但文本绘制在位图的中心

public Bitmap drawTextToBitmap(Context gContext,
                               Bitmap bitmap,
                               String gText) {
    Resources resources = gContext.getResources();
    float scale = resources.getDisplayMetrics().density;
    android.graphics.Bitmap.Config bitmapConfig =
            bitmap.getConfig();
    if (bitmapConfig == null) {
        bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
    }
    bitmap = bitmap.copy(bitmapConfig, true);
    Canvas canvas = new Canvas(bitmap);
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setColor(getResources().getColor(R.color.fujiColor));
    paint.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/DS-DIGI.TTF"));
    paint.setTextSize((int) (14 * scale));
    paint.setShadowLayer(1f, 0f, 1f, getResources().getColor(R.color.fujiShadowColor));
    Rect bounds = new Rect();
    paint.getTextBounds(gText, 0, gText.length(), bounds);
    int x = (bitmap.getWidth() - bounds.width()) / 2;
    int y = (bitmap.getHeight() + bounds.height()) / 2;
    canvas.drawText(gText, x, y, paint);
    return bitmap;
}

我需要的是类似的东西:

谢谢。

【问题讨论】:

    标签: java android canvas bitmap drawtext


    【解决方案1】:

    正如official docs 中提到的,文本是以 (x,y) 值作为原点绘制的。更改 x,y 值。以下内容应该可以工作。

    int horizontalSpacing = 24;
    int verticalSpacing = 36;
    int x = horizontalSpacing;//(bitmap.getWidth() - bounds.width()) / 2;
    int y = bitmap.getHeight()-verticalSpacing;//(bitmap.getHeight() + bounds.height()) / 2;
    

    【讨论】:

    • 非常感谢您的回答,请您解释一下为什么是 24 和为什么是 36
    • 没有什么特别的原因,我只是习惯于使用 4 或 8 的倍数来确定间距/大小 (material design)。垂直间距设置得更高,因为 y、g、q 等字符的文本会“低于原点”。
    猜你喜欢
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多