在Android中,StaticLayout
用于將文本內容布局化為一個矩形區域
import android.content.Context;
import android.graphics.Canvas;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
public class StaticLayoutExample {
public static void main(String[] args) {
Context context = new Context();
String text = "Hello, this is a static layout example!";
int width = 200;
int height = 100;
StaticLayout staticLayout = createStaticLayout(context, text, width, height);
drawStaticLayout(staticLayout);
}
private static StaticLayout createStaticLayout(Context context, String text, int width, int height) {
TextPaint textPaint = new TextPaint();
textPaint.setTextSize(16);
textPaint.setColor(0xFF000000);
int numberOfLines = 3;
StaticLayout staticLayout = new StaticLayout(text, 0, text.length(), textPaint, width, Layout.Alignment.ALIGN_NORMAL, numberOfLines, 0);
return staticLayout;
}
private static void drawStaticLayout(StaticLayout staticLayout) {
Canvas canvas = new Canvas();
canvas.drawColor(0xFFFFFFFF); // Set background color
staticLayout.draw(canvas);
}
}
在這個示例中,我們首先創建了一個Context
對象,然后定義了一個字符串text
和布局的寬度和高度。接下來,我們使用createStaticLayout
方法創建一個StaticLayout
實例,傳入文本、寬度、高度等參數。最后,我們使用drawStaticLayout
方法將StaticLayout
繪制到一個Canvas
上。