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

问题描述 投票:1回答:1

我想在位图图像上添加一个字符串。我有一个方法drawTextToBitmap,该方法可以成功在位图图像上放置字符串。但是我的位图图像像pinmark图像一样很小。此函数根据位图设置字符串高度和宽度。我要放置的字符串超过位图图像。因此,请帮助我解决问题。

我正在使用的以下获取位图的方法:

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;
}
android bitmap android-bitmap
1个回答
2
投票
尝试一下:

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

© www.soinside.com 2019 - 2024. All rights reserved.