美文网首页Android开发经验谈
TextView 竖直显示文字,并做对应的旋转,使他在布局中也是

TextView 竖直显示文字,并做对应的旋转,使他在布局中也是

作者: InFatuated | 来源:发表于2024-02-29 10:21 被阅读0次
    import android.content.Context
    import android.graphics.Canvas
    import android.util.AttributeSet
    import android.view.Gravity
    import androidx.appcompat.widget.AppCompatTextView
    
    
    class VerticalTextView(context: Context, attrs: AttributeSet) :
        AppCompatTextView(context, attrs) {
        private var topDown = false
        init {
            val gravity = gravity
            topDown =
                if (Gravity.isVertical(gravity) && gravity and Gravity.VERTICAL_GRAVITY_MASK == Gravity.BOTTOM) {
                    setGravity(gravity and Gravity.HORIZONTAL_GRAVITY_MASK or Gravity.TOP)
                    false
                } else true
        }
    
        override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
            super.onMeasure(heightMeasureSpec, widthMeasureSpec)
            setMeasuredDimension(measuredHeight, measuredWidth)
        }
    
        override fun onDraw(canvas: Canvas) {
            val textPaint = paint
            textPaint.setColor(currentTextColor)
            textPaint.drawableState = drawableState
            canvas.save()
    
            //默认为文字朝右,即旋转了90度
            //设置android:gravity="bottom"时,他会文字朝向左,即旋转了270度
            if (topDown) {
                canvas.translate(width.toFloat(), 0f)
                canvas.rotate(90f)
            } else {
                canvas.translate(0f, height.toFloat())
                canvas.rotate(-90f)
            }
            canvas.translate(getCompoundPaddingLeft().toFloat(), getExtendedPaddingTop().toFloat())
            layout.draw(canvas)
            canvas.restore()
        }
    }
    

    相关文章

      网友评论

        本文标题:TextView 竖直显示文字,并做对应的旋转,使他在布局中也是

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