Tôi cũng phải đối mặt với cùng một vấn đề khi phải đảm bảo văn bản phù hợp với một hộp cụ thể. Sau đây là giải pháp hiệu quả nhất và chính xác nhất mà tôi có cho nó tại thời điểm này:
/**
* A paint that has utilities dealing with painting text.
* @author <a href="maillto:nospam">Ben Barkay</a>
* @version 10, Aug 2014
*/
public class TextPaint extends android.text.TextPaint {
/**
* Constructs a new {@code TextPaint}.
*/
public TextPaint() {
super();
}
/**
* Constructs a new {@code TextPaint} using the specified flags
* @param flags
*/
public TextPaint(int flags) {
super(flags);
}
/**
* Creates a new {@code TextPaint} copying the specified {@code source} state.
* @param source The source paint to copy state from.
*/
public TextPaint(Paint source) {
super(source);
}
// Some more utility methods...
/**
* Calibrates this paint's text-size to fit the specified text within the specified width.
* @param text The text to calibrate for.
* @param boxWidth The width of the space in which the text has to fit.
*/
public void calibrateTextSize(String text, float boxWidth) {
calibrateTextSize(text, 0, Float.MAX_VALUE, boxWidth);
}
/**
* Calibrates this paint's text-size to fit the specified text within the specified width.
* @param text The text to calibrate for.
* @param min The minimum text size to use.
* @param max The maximum text size to use.
* @param boxWidth The width of the space in which the text has to fit.
*/
public void calibrateTextSize(String text, float min, float max, float boxWidth) {
setTextSize(10);
setTextSize(Math.max(Math.min((boxWidth/measureText(text))*10, max), min));
}
}
Điều này chỉ cần tính toán kích thước chính xác hơn là chạy thử nghiệm/kiểm tra lỗi.
Bạn có thể sử dụng nó như thế này:
float availableWidth = ...; // use your text view's width, or any other width.
String text = "Hi there";
TextPaint paint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
paint.setTypeface(...);
paint.calibrateTextSize(text, availableWidth);
Hoặc cách khác, nếu bạn muốn cung cấp thùng rác:
/**
* Calibrates this paint's text-size to fit the specified text within the specified width.
* @param paint The paint to calibrate.
* @param text The text to calibrate for.
* @param min The minimum text size to use.
* @param max The maximum text size to use.
* @param boxWidth The width of the space in which the text has to fit.
*/
public static void calibrateTextSize(Paint paint, String text, float min, float max, float boxWidth) {
paint.setTextSize(10);
paint.setTextSize(Math.max(Math.min((boxWidth/paint.measureText(text))*10, max), min));
}
Sử dụng như sau:
float availableWidth = ...; // use your text view's width, or any other width.
String text = "Hi there";
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setTypeface(...);
calibrateTextSize(paint, text, 0, Float.MAX_VALUE, availableWidth);
Kiểm tra câu trả lời ở đây http://stackoverflow.com/questions/7259016/scale-text-in-a-view-to-fit/7259136#7259136 – Ronnie