android - 如何在 Android 中的位图图像上添加字符串?

标签 android bitmap android-bitmap

我想在位图图像上添加一个字符串。我有一个方法drawTextToBitmap,这个方法成功地将字符串放在位图图像上。但是我的位图图像非常小,就像pinmark图像一样。这个函数集基于位图高度和宽度的字符串。我想放置超出位图图像的字符串。所以请帮我解决问题。

Following method i am using to get bitmap :

public Bitmap drawTextToBitmap(Context gContext, int gResId, String gText) {
    Resources resources = gContext.getResources();
    float scale = resources.getDisplayMetrics().density;
    Bitmap bitmap = BitmapFactory.decodeResource(resources, gResId);

    android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
    // set default bitmap config if none
    if (bitmapConfig == null) {
        bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
    }
    // resource bitmaps are imutable,
    // so we need to convert it to mutable one
    bitmap = bitmap.copy(bitmapConfig, true);

    Canvas canvas = new Canvas(bitmap);
    // new antialised Paint
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    // text color - #3D3D3D
    paint.setColor(Color.BLACK);
    // text size in pixels
    paint.setTextSize((int) (70 * scale));
    // text shadow
    paint.setShadowLayer(1f, 0f, 1f, Color.BLACK);

    // draw text to the Canvas center
    Rect bounds = new Rect();
    paint.getTextBounds(gText, 0, gText.length(), bounds);
    int m = (bitmap.getWidth() - bounds.width()) / 2;
    int l = (bitmap.getHeight() + bounds.height()) / 2;

    canvas.drawText(gText, 1000, l, paint);

    return bitmap;
}

最佳答案

试试这个:

public static Bitmap drawStringonBitmap(Bitmap src, String string, Point location, int color, int alpha, int size, boolean underline,int width ,int height) {

    Bitmap result = Bitmap.createBitmap(width, height, src.getConfig());

    Canvas canvas = new Canvas(result);
    canvas.drawBitmap(src, 0, 0, null);
    Paint paint = new Paint();
    paint.setColor(color);
    paint.setAlpha(alpha);
    paint.setTextSize(size);
    paint.setAntiAlias(true);
    paint.setUnderlineText(underline);
    canvas.drawText(string, location.x, location.y, paint);

    return result;
}

关于android - 如何在 Android 中的位图图像上添加字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59107580/

相关文章:

android - 我可以使用 Glide 获得精炼/所需的位图以在 Canvas 上绘制吗?

java - 将 RGB 转换为位图中的 X 和 Y

Android 应用程序未关闭

java - 如何将 onClickLisntener 函数分配给我的适配器的元素?

android - 如何在不影响位图大小的情况下降低位图质量

java - 无法将 GridView 内的 ImageView 设置为从 Drawable 转换的 Bitmap

android - ExifInterface 始终返回 0 方向

android - 将图像从 DCIM 文件夹复制到另一个文件夹会导致图像质量下降

android - ListView 行中 ImageView 的圆角

Android Sqlite 存储限制