首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >绘图StaticLayout无法正常工作

绘图StaticLayout无法正常工作
EN

Stack Overflow用户
提问于 2017-09-16 20:10:35
回答 1查看 701关注 0票数 2

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

代码语言:javascript
复制
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();
    }
}

这段代码只是用来测试它是否正常工作,而且效率不高。哪个部分是错误的,并导致它无法呈现文本?

EN

回答 1

Stack Overflow用户

发布于 2018-03-15 18:33:17

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46253749

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档