美文网首页
垂直方向上可换行的TextView

垂直方向上可换行的TextView

作者: 陈沉成染 | 来源:发表于2019-09-27 19:23 被阅读0次

根据view的高度自动换行
主要是通过staticlayout 绘制文字
通过canvas 的旋转和平移达到效果

  public class StaticLayoutView extends View {
    private StaticLayout staticLayout;
    private TextPaint textPaint;
    private String text;
    private int max = 0;
    private float sp;

    public StaticLayoutView(Context context) {
        this(context, null);
    }
    public StaticLayoutView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
        initView();
    }

    public StaticLayoutView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.StaticLayoutView);
        sp = typedArray.getDimensionPixelSize(R.styleable.StaticLayoutView_Sp,18);
        initView();
    }
    private void initView(){
        textPaint=new TextPaint(Paint.ANTI_ALIAS_FLAG);
        textPaint.setColor(Color.RED);
        textPaint.setStyle(Paint.Style.FILL);
        textPaint.setTextSize(sp);
        text="在Android开发中,Canvas.drawText不会换行,即使一个很长的字符串也只会显示一行,超出部分会隐藏在屏幕之外.StaticLayout是android中处理文字的一个工具类,StaticLayout 处理了文字换行的问题";
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        max = h;
        staticLayout=new StaticLayout(text, textPaint,max, Layout.Alignment.ALIGN_CENTER, 1.0f,0.0f , false);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.rotate(-90.0F);
        canvas.translate((float)(-this.getHeight()), 0.0F);
        staticLayout.draw(canvas);
    }

    public void setText(String text){
        if (text != null){
            this.text = text;
            staticLayout=new StaticLayout(text, textPaint, getWidth(), Layout.Alignment.ALIGN_NORMAL, 1.0f,0.0f , false);
            invalidate();
        }
    }
}

MainActivity 的XML代码

  <com.chen.work.MoreThreadTest.StaticLayoutView
        android:id="@+id/vt_text"
        android:layout_width="100dp"
        android:layout_height="100dp"
        app:Sp="18sp"
        />
   <declare-styleable name="StaticLayoutView">
        <attr name="Sp" format="dimension"></attr>
    </declare-styleable>

效果

image.png

相关文章

网友评论

      本文标题:垂直方向上可换行的TextView

      本文链接:https://www.haomeiwen.com/subject/waemyqtx.html