我有一个按钮,想要将它放在45度角上。但是不知道为什么我做不到。
有没有人能够提供代码来实现这个效果?
API 11为所有视图添加了一个setRotation()方法。
您可以创建一个动画并将其应用于按钮视图。例如:
// Locate view
ImageView diskView = (ImageView) findViewById(R.id.imageView3);
// Create an animation instance
Animation an = new RotateAnimation(0.0f, 360.0f, pivotX, pivotY);
// Set the animation's parameters
an.setDuration(10000); // duration in ms
an.setRepeatCount(0); // -1 = infinite repeated
an.setRepeatMode(Animation.REVERSE); // reverses each repeat
an.setFillAfter(true); // keep rotation after animation
// Aply animation to image view
diskView.setAnimation(an);
扩展TextView
类并覆盖onDraw()
方法。确保父视图足够大,能够处理旋转按钮而不会将其裁剪。
@Override
protected void onDraw(Canvas canvas) {
canvas.save();
canvas.rotate(45,<appropriate x pivot value>,<appropriate y pivot value>);
super.onDraw(canvas);
canvas.restore();
}
我只是在我的代码中使用了简单的一行代码,它起作用了:
myCusstomView.setRotation(45);
XML中的一行
<View
android:rotation="45"
... />
应用旋转动画(没有持续时间,因此没有动画效果)比调用View.setRotation()或覆盖View.onDraw方法更简单。
// substitude deltaDegrees for whatever you want
RotateAnimation rotate = new RotateAnimation(0f, deltaDegrees,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
// prevents View from restoring to original direction.
rotate.setFillAfter(true);
someButton.startAnimation(rotate);
rotate()
旋转视图不会影响视图的测量大小。结果是,旋转的视图可能被裁剪或不适合父布局。然而,这个库可以解决这个问题:https://github.com/rongi/rotate-layout。
结合 @Rudi 和 @Pete 的回答,我创建了一个旋转动画,保持按钮功能在旋转后仍然可用。
setRotation() 方法可以保留按钮的功能。
代码示例:
Animation an = new RotateAnimation(0.0f, 180.0f, mainLayout.getWidth()/2, mainLayout.getHeight()/2);
an.setDuration(1000);
an.setRepeatCount(0);
an.setFillAfter(false); // DO NOT keep rotation after animation
an.setFillEnabled(true); // Make smooth ending of Animation
an.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {}
@Override
public void onAnimationRepeat(Animation animation) {}
@Override
public void onAnimationEnd(Animation animation) {
mainLayout.setRotation(180.0f); // Make instant rotation when Animation is finished
}
});
mainLayout.startAnimation(an);
mainLayout是一个(LinearLayout)字段。
如前所述,最简单的方法是使用API 11及以上版本提供的rotation
:
android:rotation="90" // in XML layout
view.rotation = 90f // programatically
// top left
view.pivotX = 0f
view.pivotY = 0f
// bottom right
view.pivotX = width.toFloat()
view.pivotY = height.toFloat()
...
onCreate()
或Fragment的onCreateView(...)
中,宽度和高度都等于0,因为视图尚未被测量。您可以使用Android KTX的doOnPreDraw
扩展来访问它,例如:view.apply {
doOnPreDraw {
pivotX = width.toFloat()
pivotY = height.toFloat()
}
}
如果您希望通过动画使其动态化:
view.animate()
.rotation(180)
.start();
这就是它