[英]how to rotate button about its center in android
嗨,在我的應用程序中,我試圖旋轉按鈕關於它的中心,但它不是基於它的中心旋轉,而是從它的位置移動。下面是我的代碼,請幫助我如何解決這個問題。
public class example extends Activity {
float newAngle,oldAngle=0;
int flag=0;
int n=340;
RotateAnimation animation,animation1;
Button arrow;
Button left,right;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
arrow=(Button)findViewById(R.id.img);
left=(Button)findViewById(R.id.left);
right=(Button)findViewById(R.id.right);
final int width = arrow.getWidth();
final int height = arrow.getHeight();
left.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(flag>=0)
{
newAngle = oldAngle+ 30;
oldAngle=newAngle;
}
flag++;
Log.i("flag",""+flag);
animation = new RotateAnimation(oldAngle, newAngle);
animation.setFillAfter(true);
animation.setDuration(200);
arrow.startAnimation(animation);
}
});
}
}
更輕松...
new RotateAnimation(_oldAngle, _newAngle, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
完整的例子:
public class MyActivity extends Activity implements View.OnClickListener {
private ImageView _image;
private float _newAngle, _oldAngle;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
_image = (ImageView) findViewById(R.id.image);
}
public void onClick(View view) {
if (view.getId() == R.id.button) {
_newAngle = _oldAngle + 30;
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) _image.getLayoutParams();
int centerX = layoutParams.leftMargin + (_image.getWidth()/2);
int centerY = layoutParams.topMargin + (_image.getHeight()/2);
RotateAnimation animation = new RotateAnimation(_oldAngle, _newAngle, centerX, centerY);
animation.setDuration(0);
animation.setRepeatCount(0);
animation.setFillAfter(true);
_image.startAnimation(animation);
_oldAngle = _newAngle;
}
}
}
最簡單的解決方案值得一提:
button.setRotation( angle );
把它放在你的onClick
方法中。 例如:
public void onClick( View v ) { v.setRotation( v.getRotation() + 30f ); }
請參閱View API 。
采用
RotateAnimation(float fromDegrees,float toDegrees,float pivotX,float pivotY)
pivotX,pivotY - 按鈕中心的坐標。 看起來你的角度是一樣的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.