在左下角的位图上绘制文本

时间:2019-07-09 10:12:28

标签: java android canvas bitmap drawtext

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

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

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

我需要的东西与此类似:

enter image description here

谢谢。

1 个答案:

答案 0 :(得分:1)

official docs中所述,以(x,y)值作为原点绘制文本。更改xy的值。遵循以下内容应该可以。

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