Created
February 2, 2015 23:22
-
-
Save tokudu/601320d9edb978bcbc31 to your computer and use it in GitHub Desktop.
How to create BackgroundColorSpan with padding
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
i work with a similar task, and also can not solve the problem with gravity = center.
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.
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
Thanks for the code! Can this be modified to work with gravity="center" on the textView?