2

I want to rotate a Button view by 45 degrees. For that I have written the code which is shown below. Now rather than rotating the Button itself, the text or label on the Button is getting rotated. But I want the Button to get rotated by 45 degrees. How can I accomplish this?

public class MyButton extends Button {

    public float degrees;
    public float sWidth;
    public float sHeight;

    public MyButton(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub

        canvas.save();
        canvas.rotate(45.0f);
        super.onDraw(canvas);

        canvas.restore();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        // TODO Auto-generated method stub
        super.onSizeChanged(w, h, oldw, oldh);
        sWidth=w;
        sHeight=h;
    }
}
Thomas Keller
  • 5,933
  • 6
  • 48
  • 80
Prashant Kumar
  • 134
  • 1
  • 2
  • 9

4 Answers4

7

This link may help.

I believe you need to apply RotateAnimation to the view, with fillAfter set to true to keep it's angle. The above example works on the layout, but you could apply the animation to a view (in your case, the button).

Community
  • 1
  • 1
Ricky
  • 7,785
  • 2
  • 34
  • 46
3

if you want to have an stable rotated Button use the following extended Button. Maybe you need getWidth() / 2, getHeight() / 2:

public class RotateButton extends Button{

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

    public RotateButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.save();
        canvas.rotate(45, getWidth() / 2, getHeight() / 2);
        super.onDraw(canvas);
        canvas.restore();
    }

}

and in your layout:

<com.samples.myapp.ui.RotateButton
        android:layout_height="wrap_content" android:id="@+id/MyBtn"
        android:padding="5dip" android:textColor="@color/darkGreen"
        android:textSize="16dip" android:text="TextView"
        android:layout_width="wrap_content"></com.samples.myapp.ui.RotateButton>
Bob
  • 22,810
  • 38
  • 143
  • 225
  • I have a image on the button. After i rotate the button with the code you provide the image edges get distorted and loss its sharpness. – Gem Feb 21 '14 at 06:24
1

If you're happy to use an animation, on API >= 11, I would go for:

ObjectAnimator.ofFloat(buttonView, "rotation", 0, 45).start();
Adi B
  • 819
  • 1
  • 8
  • 11
0

If you simply want to rotate the button and the text within it use android:rotation="angle by which you want to rotate" within the xml file for the button

Light
  • 1