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

4
我希望在位图图像上添加一个字符串。我有一个名为“drawTextToBitmap”的方法,这个方法可以成功地将字符串放置在位图图像上。但是我的位图图像非常小,例如标记图像。该函数根据位图的高度和宽度设置字符串。我想把字符串放在位图图像之外。所以请帮我解决这个问题。
以下是我正在使用的获取位图的方法:
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;
}
1个回答

10

试试这个:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接