如何在android中旋转按钮视图
我想将按钮视图旋转45度。为此,我编写了如下所示的代码。现在,按钮上的文本或标签正在旋转,而不是旋转按钮本身。但我想让按钮旋转45度。我怎样才能做到这一点如何在android中旋转按钮视图,android,Android,我想将按钮视图旋转45度。为此,我编写了如下所示的代码。现在,按钮上的文本或标签正在旋转,而不是旋转按钮本身。但我想让按钮旋转45度。我怎样才能做到这一点 public class MyButton extends Button { public float degrees; public float sWidth; public float sHeight; public MyButton(Context context) { super(c
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;
}
}
我认为您需要对视图应用
RotateAnimation
,将fillAfter
设置为true以保持其角度。上面的示例适用于布局,但您可以将动画应用于视图(在您的示例中为按钮)。如果您希望有一个稳定的旋转按钮,请使用以下扩展按钮。也许您需要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>
如果您愿意在API>=11上使用动画,我会选择:
ObjectAnimator.ofFloat(buttonView, "rotation", 0, 45).start();
如果您只想旋转按钮和其中的文本,请在按钮的xml文件中使用android:rotation=“angle by which you want rotate”您的目标是哪个API级别?我在按钮上有一个图像。在我用代码旋转按钮后,图像边缘会扭曲并失去清晰度。