Created
June 29, 2016 11:01
-
-
Save acmi/5cbb85fdc0e2e8d304eb2fdfa2af1dda to your computer and use it in GitHub Desktop.
Android text justify
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.content.Context; | |
import android.graphics.Canvas; | |
import android.text.Layout; | |
import android.text.StaticLayout; | |
import android.util.AttributeSet; | |
import android.widget.TextView; | |
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
public class JustifyTextView extends TextView { | |
private static final Pattern BLANKS = Pattern.compile("\\s+"); | |
public JustifyTextView(Context context, AttributeSet attrs) { | |
super(context, attrs); | |
} | |
@Override | |
protected void onDraw(Canvas canvas) { | |
getPaint().setColor(getCurrentTextColor()); | |
getPaint().drawableState = getDrawableState(); | |
int lineY = getPaddingTop(); | |
lineY += 2 + getLineHeight() / 2; //FIXME | |
Layout layout = getLayout(); | |
for (int i = 0; i < layout.getLineCount(); i++) { | |
int lineStart = layout.getLineStart(i); | |
int lineEnd = layout.getLineEnd(i); | |
CharSequence line = getText().subSequence(lineStart, lineEnd); | |
if (line.length() != 0 && i < layout.getLineCount() - 1) { | |
float lineWidth = StaticLayout.getDesiredWidth(line, getPaint()); | |
int viewWidth = getMeasuredWidth() - (getPaddingLeft() + getPaddingRight()); | |
drawScaledText(canvas, line, lineY, lineWidth, viewWidth); | |
} else { | |
canvas.drawText(line.toString(), getPaddingLeft(), lineY, getPaint()); | |
} | |
lineY += getLineHeight(); | |
} | |
} | |
private void drawScaledText(Canvas canvas, CharSequence line, int lineY, float lineWidth, int viewWidth) { | |
float x = getPaddingLeft(); | |
Matcher matcher = BLANKS.matcher(line); | |
if (matcher.find() && matcher.start() == 0) { | |
String blanks = matcher.group(); | |
canvas.drawText(blanks, x, lineY, getPaint()); | |
float bw = StaticLayout.getDesiredWidth(blanks, getPaint()); | |
x += bw; | |
line = line.subSequence(matcher.end(), line.length()); | |
} | |
float d = (viewWidth - lineWidth) / (line.length() - 1); | |
for (int i = 0; i < line.length(); i++) { | |
String c = String.valueOf(line.charAt(i)); | |
float cw = StaticLayout.getDesiredWidth(c, getPaint()); | |
canvas.drawText(c, x, lineY, getPaint()); | |
x += cw + d; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment