How to rotate TextView without clipping its bounds?

前端 未结 4 1964
南旧
南旧 2021-02-08 10:41

I\'m trying to rotate my subclass of TextView using canvas.rotate():

canvas.save();

final int w = getWidth();
final int h = getHeight(         


        
4条回答
  •  天命终不由人
    2021-02-08 11:04

    I think that the entire problem here, is that you are using WRAP_CONTENT. The clip rect for the view, when you do that, is the size of the text content. The simplest way to fix the problem is to use padding. Something like this, works fine for me:

    
    

    Of course, if you do it this way, you'll have to choose a slightly different padding for each content. If you can't do that, override onMeasure, so that does exactly what TextView's onMeasure does, then adds corresponding padding, as necessary for the rotation.

    Added later: Actually, this was kinda fun to figure out. I have the following onMeasure, that works pretty well:

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int w = getMeasuredWidth();
        int h = getMeasuredHeight();
        w = (int) Math.round(w * cosA + h * sinA);
        h = (int) Math.round(h * cosA + w * sinA);
        setMeasuredDimension(w, h);
    }
    

    The only remaining problem is that the text gets wrapped according to the pre-rotation dimensions. You'd have to fix that too...

    sinA and cosA are computed when mAngle is set.

提交回复
热议问题