Android画布不会在我的位图上绘制文本

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

我正在尝试从用户那里获取文本输入并使用Canvas在图像上绘制,但图像保存时没有应该绘制的内容。现在,我只是想在我担心字体,颜色,样式等之前获取图像上的文字。

这是我的代码:

 public void createBitmapAndSave(ImageView img){
        BitmapDrawable bitmapDrawable = ((BitmapDrawable) img.getDrawable());
        Bitmap bitmap = bitmapDrawable.getBitmap();
        Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);

        Canvas canvas = new Canvas(mutableBitmap);
        Paint paint = new Paint();
        paint.setColor(Color.BLUE);
        paint.setTextSize(200);
        paint.setStyle(Paint.Style.FILL);
        paint.setShadowLayer(10f, 10f, 10f, Color.BLACK);

        String topText = topTextView.getText().toString();
        String bottomText = bottomTextView.getText().toString();

        canvas.drawText(topText, 0, 0, paint);
        canvas.drawText(bottomText, 50, 50, paint);

        File file;
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);

        String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath();
        file = new File(path + "/SimpliMeme/" + timeStamp + "-" + counter + ".jpg");
        file.getParentFile().mkdir();

        try{
            OutputStream stream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
            stream.flush();
            stream.close();
            Toast.makeText(getContext(), "Meme Saved", Toast.LENGTH_SHORT).show();
        }
        catch (IOException e){ e.printStackTrace();}

        Uri contentUri = Uri.fromFile(file);
        mediaScanIntent.setData(contentUri);
        Objects.requireNonNull(getContext()).sendBroadcast(mediaScanIntent);
        counter++;
    }

目前,基于我在其他SO帖子中看到的示例,我只有2个.drawText()实现。我的假设是文本不可见,并且没有对图像进行任何更改,因为我没有为paint对象提供任何属性。

java android android-canvas android-bitmap android-paint
1个回答
1
投票

您没有看到任何更改的主要问题是您对mutableBitmap进行了更改,但将原始bitmap保存到磁盘。

将前两个(甚至三个)语句连接在一起可以避免这种情况:

final Bitmap bitmap = bitmapDrawable.getBitmap()
        .copy(Bitmap.Config.ARGB_8888, true);

你不需要其他地方的原始位图,这有效地防止你犯错误。不要做你不需要做的事。

一些技巧:

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