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

时间:2015-07-01 15:45:37

标签: android bitmap android-bitmap

我想在Bitmap Image上添加一个字符串。我有一个函数drawTextToBitmap,这个函数在Bitmap图像上成功地放置了字符串。但是我的Bitmap图像非常像pinmark图像。这个函数设置字符串基于位图的高度和宽度。我们想要放置超过Bitmap Image的字符串。所以请帮我解决问题。

功能:

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 个答案:

答案 0 :(得分:1)

试试这个:

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