TextView在屏幕上具有大方块的形式。必须调整里面的文本大小,使其尽可能大并适合整个 TextView 空间。
假设文本是"hello",结果将是屏幕上的一个大大的"hello"。
我在这里问如何将字体调整为正确的像素量,前提是正方形具有已知大小。
我知道显示的字符串不能完全平方,但主要目标是文本在 TextView 区域内尽可能大。
Override following method:
@Override
public void onWindowFocusChanged (boolean hasFocus) {
// the height will be set at this point
int height = myEverySoTallView.getMeasuredHeight();
int width = myEverySoTallView.getMeasuredWidth();
//as per width/height you can try modifying text size
myTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, width/SOME_CONSTANT);
}
好吧,如果您希望正常绘制文本(如在 0 度旋转中),但缩放以满足视图的边界,您可以使用如下所示的内容:
public class ScalingTextCustomTextView extends CustomTextView {
public ScalingTextCustomTextView(Context context) {
super(context);
}
public ScalingTextCustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int height = getMeasuredHeight();
refitText(this.getText().toString(), parentWidth);
this.setMeasuredDimension(parentWidth, height);
}
@Override
protected void onTextChanged(final CharSequence text, final int start, final int before, final int after) {
refitText(text.toString(), this.getWidth());
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
if(w != oldw)
refitText(this.getText().toString(), w);
}
private void refitText(String text, int textWidth) {
if(textWidth <= 0)
return;
int targetWidth = textWidth - this.getPaddingLeft() - this.getPaddingRight();
float hi = 200;
float lo = 2;
final float threshold = 0.5f;
Paint temp = new Paint();
temp.set(getPaint());
while((hi - lo) > threshold){
float size = (hi + lo) / 2;
temp.setTextSize(size);
if(temp.measureText(text) >= targetWidth)
hi = size;
else lo = size;
}
this.setTextSize(TypedValue.COMPLEX_UNIT_PX, lo);
}
}`
如果您希望它旋转 45 度,只需添加:
@Override
public void onDraw(Canvas canvas){
canvas.save();
canvas.rotate(45, canvas.getWidth() / 2, canvas.getHeight() / 2);
super.onDraw(canvas);
canvas.restore();
}
但是,如果您希望将其缩放得稍大以适合最长距离,则必须调整 refitText 以根据从左上角到右下角的距离计算目标宽度。
不过,这应该为您指明正确的方向。
我认为设置所需的文本视图大小(myTextViewSize)就足够了,然后设置文本内容(它肯定在里面,具有我想要的视图尺寸),
然后使用
Rect bounds = new Rect();
textView.getPaint().getTextBounds(textView.getText(), 0, textView.getText().length(), bounds);
int oldTextWidth=bounds.width();
float oldFontSize=textView.getTextSize();
float newFontSize=(myTextViewSize- textView.getPaddingLeft() - textView.getPaddingRight())*oldFontSize/oldTextWidth;