java - 绘图 StaticLayout 无法正常工作

标签 java android staticlayout

我已经实现了一个带有 Text.LayoutView,我正在绘制它,但我什么也没得到。这是我的代码

public class MyEfficientTextView extends View {
    Layout textLayout;
    SpannableStringBuilder spannableStringBuilder;
    int width = 0, height = 0;
    TextPaint textPaint;
    CharSequence text;

    public MyEfficientTextView(Context context) {
        this(context, null, 0);
    }

    public MyEfficientTextView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyEfficientTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        spannableStringBuilder = new SpannableStringBuilder();
    }

    public void setText(CharSequence charSequence) {
        text = charSequence;
        spannableStringBuilder.clear();
        spannableStringBuilder.append(text);
        textPaint = new TextPaint();
        textPaint.setAntiAlias(true);
        textPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
        textPaint.setColor(getResources().getColor(R.color.textColor));
        textLayout = new StaticLayout(spannableStringBuilder, textPaint, width, Layout.Alignment.ALIGN_NORMAL, 1, 0, false);
        invalidate();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if (w != width) {
            width = w;
            setText(text);
        }
        height = h;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.save();
        if (textLayout != null) {
            canvas.translate(getPaddingLeft(), getPaddingTop());
            textLayout.draw(canvas);
        }
        canvas.restore();
    }
}

这段代码只是为了测试它是否有效,效率不高。哪一部分是错误的,导致它无法呈现文本?

最佳答案

您应该覆盖 onMeasure 并设置 View 宽度/高度。您的示例代码将导致默认宽度/高度(可能为 0)。

关于java - 绘图 StaticLayout 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46253749/

相关文章:

android - LineSpace 如何影响单行文本中的 StaticLayout 高度

android - 什么是 Android 中的领先利润率?

java - Kotlin:集合既没有泛型类型也没有 OneToMany.targetEntity()

java - 具有 GSON 的 Android Volley 库无法将数据设置为 POJO 类

android - 如何解决此抽屉导航问题

Android 中的 java.lang.NullPointerException 错误

android - TextView 和 EditText 中的 TextRendering

Java - JEditorPane - 超链接问题

java - 什么时候使用 "Dynamic Proxy class"或 "standard proxy"模式?

java - 膨胀 fragment 时出错