在画布变换后更新视图边界(旋转,缩放,变换)

时间:2013-09-04 23:16:04

标签: java android android-canvas android-ui

在尝试将更改应用于旋转,缩放和变换后,我试图弄清楚如何更新视图的边界以匹配画布。

这是我的自定义textview类。我按照我想要的方式旋转工作,但是视图没有环绕我的画布。

public class RDTextView extends TextView {

public int angle = 0;

public RDTextView(Context context) {
    super(context);
}

@Override
protected void onDraw(Canvas canvas)
{ // Save the current matrix
    canvas.save();
    // Rotate this View at its center
    canvas.rotate(angle,this.getWidth()/2, this.getHeight()/2);
    // Draw it --- will add scale
    super.onDraw(canvas);
    // Restore to the previous matrix
    canvas.restore();
}

我的问题是我在视图周围有一个边框但是在我改变角度之后它不遵循画布形状。

Before rotation After rotation

旋转后边框不变,但我想更新它以匹配内容。

1 个答案:

答案 0 :(得分:0)

我刚刚为我的需求制作了以下代码。

    import java.awt.Graphics;
    import java.awt.Graphics2D;

    import javax.swing.JLabel;


    public class RotatedLabel extends JLabel {

        //we need to remember original size
        private int originalWidth = 0;
        private int originalHeight = 0;

        //I do rotation around the center of label, so save it too
        private int originX = 0;
        private int originY = 0;

        public RotatedLabel(String text, int horizotalAlignment) {
            super(text, horizotalAlignment);
        }

        @Override
        public void setBounds(int x, int y, int width, int height) {
            //save new data
            originX = x + width / 2;
            originY = y + height / 2;
            originalWidth = width;
            originalHeight = height;
            super.setBounds(x, y, width, height);
        };

        @Override
        public void paint(Graphics g) {
            Graphics2D g2d = (Graphics2D) g;

            int w2 = getWidth() / 2;
            int h2 = getHeight() / 2;

            double angle = -Math.PI / 2;//it's our angle

            //now we need to recalculate bounds
            int newWidth = (int)Math.abs(originalWidth * Math.cos(angle) + originalHeight * Math.sin(angle));
            int newHeight = (int)Math.abs(originalWidth * Math.sin(angle) + originalHeight * Math.cos(angle));

            g2d.rotate(angle, w2, h2);
            super.paint(g);

            //set new bounds
            super.setBounds(originX - newWidth / 2, originY - newHeight / 2, newWidth, newHeight);
        }
    }