【问题标题】:How to rotate a Button View in android如何在android中旋转按钮视图
【发布时间】:2011-10-25 07:55:42
【问题描述】:

我想将 Button 视图旋转 45 度。为此,我编写了如下所示的代码。现在不是旋转按钮本身,而是旋转按钮上的文本或标签。但我希望按钮旋转 45 度。我怎样才能做到这一点?

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;
    }
}

【问题讨论】:

  • 您的目标是哪个 API 级别?

标签: android


【解决方案1】:

This link may help.

我相信您需要将RotateAnimation 应用于视图,并将fillAfter 设置为true 以保持其角度。上面的示例适用于布局,但您可以将动画应用于视图(在您的情况下为按钮)。

【讨论】:

    【解决方案2】:

    如果您想要一个稳定的旋转按钮,请使用以下扩展按钮。也许你需要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();
        }
    
    }
    

    在你的布局中:

    <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>
    

    【讨论】:

    • 按钮上有一张图片。在我使用您提供的代码旋转按钮后,图像边缘会失真并失去其清晰度。
    【解决方案3】:

    如果您愿意在 API >= 11 上使用动画,我会选择:

    ObjectAnimator.ofFloat(buttonView, "rotation", 0, 45).start();
    

    【讨论】:

      【解决方案4】:

      如果您只是想旋转按钮及其中的文本,请在按钮的 xml 文件中使用 android:rotation="angle by which you want to rotate"

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-19
        • 1970-01-01
        • 2010-12-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多