Skip to content

Instantly share code, notes, and snippets.

@tokudu
Created February 2, 2015 23:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tokudu/601320d9edb978bcbc31 to your computer and use it in GitHub Desktop.
Save tokudu/601320d9edb978bcbc31 to your computer and use it in GitHub Desktop.
How to create BackgroundColorSpan with padding
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.text.style.LineBackgroundSpan;
public class PaddingBackgroundColorSpan implements LineBackgroundSpan {
private int mBackgroundColor;
private int mPadding;
private Rect mBgRect;
public PaddingBackgroundColorSpan(int backgroundColor, int padding) {
super();
mBackgroundColor = backgroundColor;
mPadding = padding;
// Precreate rect for performance
mBgRect = new Rect();
}
@Override
public void drawBackground(Canvas c, Paint p, int left, int right, int top, int baseline, int bottom, CharSequence text, int start, int end, int lnum) {
final int textWidth = Math.round(p.measureText(text, start, end));
final int paintColor = p.getColor();
// Draw the background
mBgRect.set(left - mPadding,
top - (lnum == 0 ? mPadding / 2 : - (mPadding / 2)),
left + textWidth + mPadding,
bottom + mPadding / 2);
p.setColor(mBackgroundColor);
c.drawRect(mBgRect, p);
p.setColor(paintColor);
}
}
Copy link

ghost commented Aug 30, 2015

Thanks for the code! Can this be modified to work with gravity="center" on the textView?

@abbath0767
Copy link

i work with a similar task, and also can not solve the problem with gravity = center.

@MrVitols
Copy link

MrVitols commented Oct 1, 2018

Works for text if alignment is left, but when it's centered or right, then it doesn't work draws the background for the left aligned text.
I am working with converted code from this Java code to Kotlin.

@sheamartinson
Copy link

sheamartinson commented May 21, 2019

For center-aligned text you really just need to subtract the width of the text from the width of the canvas and pad half the value on the left and right sides of the drawing Rect. F.ex.
`
val leftCalc = (right - left - it.toInt()) / 2

        bgRect.set(

            leftCalc - padding,

            top - (if (lnum == 0) padding / 2 else -1 * (padding / 2)),

            leftCalc + textWidth.toInt() + padding,

            bottom + padding / 2

        )`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment