如何组合 TextView 和图像以及 return 图像?

How to combine TextView and an image and return an image?

我在搜索结果时遇到了这个 How can I convert a View to a Drawable? 这背后的想法是我可以先将 TextView 转换为位图,然后将两个位图组合起来。但是通过将 TextView 转换为位图,它会失去我不想要的透明度。我想要 TextView 在我的 ImageView 上,但作为一个图像使用 canvas。

我的想法是创建这样的图像:

在这里,我想用白色边框的可绘制形状将文本括起来。 然后将此 Textview 放在图像上,然后将所有内容保存为位图。 请帮忙

您可以尝试在 canvas 上绘制文字和线条。
下面是在可绘制图像和 returns Bitmap.
上绘制文本的示例方法 您可以通过在 Paint 对象上调用 .setTypeface() 来设置自定义字体。
调用 canvas.drawLine() 画线。要自定义您的线条,您可以创建新的 Paint 对象,通过 .setColor().setStrokeWidth() 设置其颜色和宽度,并将其与线条坐标一起传递给 drawLine()

public Bitmap drawTextOnBitmap(Context context, int resId, String text) {

        // prepare canvas
        Resources resources = context.getResources();
        float scale = resources.getDisplayMetrics().density;
        Bitmap bitmap = BitmapFactory.decodeResource(resources, resId);

        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 immutable, so we need to convert it to mutable one
        bitmap = bitmap.copy(bitmapConfig, true);
        Canvas canvas = new Canvas(bitmap);

        // new antialiased Paint
        TextPaint paint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
        // text color - #3D3D3D
        paint.setColor(Color.rgb(61, 61, 61));
        // text size in pixels
        paint.setTextSize((int) (bitmap.getHeight() / 10 * scale));
        // text shadow
        paint.setShadowLayer(1f, 0f, 1f, Color.WHITE);

        // set text width to canvas width minus 16dp padding
        int textWidth = canvas.getWidth() - (int) (16 * scale);

        // init StaticLayout for text
        StaticLayout textLayout = new StaticLayout(text, paint, textWidth,
                Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);

        // get height of multiline text
        int textHeight = textLayout.getHeight();

        // get position of text's top left corner
        float x = (bitmap.getWidth() - textWidth) / 2;
        float y = (bitmap.getHeight() - textHeight) / 2;

        // draw text to the Canvas center
        canvas.save();
        canvas.translate(x, y);
        textLayout.draw(canvas);
        canvas.restore();

        return bitmap;
    } 

更新:
要绘制矩形,请将其添加到方法中:

        Paint p = new Paint();
        p.setStyle(Paint.Style.STROKE);
        p.setStrokeWidth(24);
        RectF rectF = new RectF(80, 150, 200, 350);
        canvas.drawRect(rectF, p);

新 RectF() 的参数:

矩形左侧的X坐标
顶部
矩形顶部的Y坐标

矩形右侧的X坐标
底部
矩形底部的Y坐标