how to draw text with background color using canvas

后端 未结 4 2096
-上瘾入骨i
-上瘾入骨i 2021-02-19 16:37

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

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

Please tell me,

4条回答
  •  遇见更好的自我
    2021-02-19 17:23

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

提交回复
热议问题