17

I have some code where I'm drawing my text on bitmap (canvas)

canvas.drawTextOnPath(Text, textPath[count], gipa, -10, text);

Please tell me, it's possible to draw this text in path(textPath) with background color?

it's full function for drawing only text

 public void drawText(float x,float y ,String Text,Canvas canvas,Paint paint1 ,int count )
        {
            float xren =text.measureText(Text.trim());

            canvas.drawTextOnPath(Text, textPath[count], gipa, -10, text);

        }

Using this function I'm drawing text on my canvas. so how to modify this function for drawing this text with background?

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
Peter
  • 2,480
  • 6
  • 39
  • 60
  • You mean test should have a color or the canvas should have a color? – Rajdeep Dua Nov 23 '11 at 12:52
  • mmmm canvas have bitmap (image), on this image im drawing text using drawTextOnPath(because i need this funciton for drawing).. i want draw this text(green text color for example ) with background only for this text(example : black) – Peter Nov 23 '11 at 12:54
  • Can't you just draw the path with a line of your desired background color and then draw the text on it? This may require insetting the path a bit. – js- Nov 23 '11 at 12:55
  • okay, can u provide some code how to draw line(or rectangle) on path with text ? please – Peter Nov 23 '11 at 12:57

4 Answers4

20

Most likely two steps are needed here. you would draw a line along path first with color for background and then draw the text as indicated. Set the thickness of the line with a paint object. Also, changing the style of the paint can help with the effect. try FILL, STROKE or FILL_AND_STROKE for different effects.

mpaint.setStyle(Paint.Style.STROKE);
mpaint.setStrokeWidth(strokeWidth);

Added sample to draw a path(rectangle) with red color:

         Paint mPaint = new Paint();
         mPaint.setColor(Color.RED);
         Path mPath = new Path();
         RectF mRectF = new RectF(20, 20, 240, 240);
         mPath.addRect(mRectF, Path.Direction.CCW);
         mPaint.setStrokeWidth(20);
         mPaint.setStyle(Paint.Style.STROKE);
         canvas.drawPath(mPath, mPaint);

Then draw text along same path (blue color):

        mPaint.setColor(Color.BLUE);
         mPaint.setStrokeWidth(0);
         mPaint.setStyle(Paint.Style.FILL);
         mPaint.setTextSize(20);
         canvas.drawTextOnPath("Draw the text, with origin at (x,y), using the specified paint, along the specified path.", mPath, 0, 5, mPaint);

results

eyespyus
  • 1,576
  • 19
  • 20
  • Thanks for the nudge in the right direction. I ended up painting the text twice. First I used a stroke, then painted over it with the text. No calculations or heavy lifting. – Abandoned Cart Feb 26 '20 at 21:21
10

If you want to make like this then implement below code snippet:

enter image description here

     /**
     * PUT THIS METHOD FOR IMPLEMENT WATER-MARK IN COMMON FILE
     */
    public static Bitmap waterMark(Bitmap src, String watermark) {
        //get source image width and height
        int w = src.getWidth();
        int h = src.getHeight();

        Bitmap result = Bitmap.createBitmap(w, h, src.getConfig());
        Canvas canvas = new Canvas(result);
        canvas.drawBitmap(src, 0, 0, null);
        Paint paint = new Paint();
        Paint.FontMetrics fm = new Paint.FontMetrics();
        paint.setColor(Color.WHITE);
        paint.getFontMetrics(fm);
        int margin = 5;
        canvas.drawRect(50 - margin, 50 + fm.top - margin,
                50 + paint.measureText(watermark) + margin, 50 + fm.bottom
                        + margin, paint);

        paint.setColor(Color.RED);

        canvas.drawText(watermark, 50, 50, paint);
        return result;
    }

// To Get Bitmap from URI:

  private Bitmap getBitmapFromUri(String photoPath) {
        Bitmap image = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
        return bitmap;
    }

// Save Image :

 private String SaveImage(Bitmap finalBitmap) {

        String root = Environment.getExternalStorageDirectory().toString();
        File myDir = new File(root + "/shareImage");
        myDir.mkdirs();
        Random generator = new Random();
        int n = 10000;
        n = generator.nextInt(n);
        String fname = "Image" + n + ".jpg";

        File file = new File(myDir, fname);
        if (file.exists()) file.delete();
        try {
            FileOutputStream out = new FileOutputStream(file);
            finalBitmap.compress(Bitmap.CompressFormat.JPEG, 20, out);
            out.flush();
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return file.getAbsolutePath();
    }

// Call like this :

                Bitmap bitmap = getBitmapFromUri(attachment.get(i).getPath()); // Enter here your Image path

                Bitmap bitmapp = waterMark(bitmap, "ENTER YOUR TEXT FOR WATERMARK LABEL");

                String path = SaveImage(bitmapp);
                Uri uri = Uri.fromFile(new File(path));

Here at last from uri you can get a new implemented watermark image.

Hope this helps you.

InsaneCat
  • 2,115
  • 5
  • 21
  • 40
6

I believe this solution is better and more flexible than drawPath.

Use this to calculate the size of the text background:

private @NonNull Rect getTextBackgroundSize(float x, float y, @NonNull String text, @NonNull TextPaint paint) {
    Paint.FontMetrics fontMetrics = paint.getFontMetrics();
    float halfTextLength = paint.measureText(text) / 2 + 5;
    return new Rect((int) (x - halfTextLength), (int) (y + fontMetrics.top), (int) (x + halfTextLength), (int) (y + fontMetrics.bottom));
}

Then draw the background as a Rect:

Rect background = getTextBackgroundSize(x, y, text, textPaint);
canvas.drawRect(background, bkgPaint);
canvas.drawText(text, x, t, textPaint);
Sir Codesalot
  • 7,045
  • 2
  • 50
  • 56
1

this method i created , it will give you better idea how easily you can do this

  public static Drawable getTextToDrawable(final String sText, final float    textSize, final int textColor, final int bgColor, final int imageSize) {

    Shape shape = new Shape() {

        @Override
        public void draw(Canvas canvas, Paint paint) {
            paint.setTextSize(spToPixel(textSize));
            int ivImageSize = SUtils.dpToPx(imageSize);
            paint.setTextAlign(Paint.Align.LEFT);
            float baseline = -paint.ascent(); // ascent() is negative
            int width = (int) (paint.measureText(sText)); // round
            int height = (int) (baseline + paint.descent());
            Bitmap image = Bitmap.createBitmap(ivImageSize, (int) (ivImageSize), Bitmap.Config.ARGB_8888);
            canvas.drawBitmap(image, ivImageSize, ivImageSize, paint);
            paint.setColor(bgColor);
            if (sText != null) {
                if (sText.length() < 3) {

                    canvas.drawCircle(ivImageSize / 2, ivImageSize / 2, ivImageSize / 2, paint);
                    paint.setColor(textColor);
                    canvas.drawText(sText, (ivImageSize - width) / 2, (height+baseline)/2, paint);
                } else {
                    canvas.drawRect(0, 0, ivImageSize, height, paint);
                    paint.setColor(textColor);
                    canvas.drawText(sText, (ivImageSize - width) / 2, baseline, paint);

                }
            }
        }
    };
    return new ShapeDrawable(shape);
}
sourav pandit
  • 8,647
  • 2
  • 19
  • 17