我尝试旋转图像。我使用runnable旋转图像,我写了循环,我想在里面循环旋转图像 这是我的来源
public void rotateimages(final View myView) {
myHandler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
double k = 30;
double speed = Math.PI / k;
for (alpa = 0; alpa < (Math.PI * 6 + res * 2 * Math.PI / 5); alpa += speed) {
myView.setRotation((float) (myView.getRotation() - alpa));
Log.e("alpa values", String.valueOf(alpa));
k = Math.min(k + 0.2, 240);
speed = Math.PI / k;
myHandler.postDelayed(this, 100);
}
// rotateimages();
}
};
myHandler.postDelayed(runnable, 180);
}
当我运行我的应用程序时,我只能旋转一次。我的代码中有什么问题?如果有人知道解决方案,请帮助我
答案 0 :(得分:1)
如果你想循环,你需要定义这个&#39; runnable&#39;再循环一次 编辑您的代码:
myHandler = new Handler();
count = 0;
public void rotateImage(final View myView, final int size) {
runnable = new Runnable() {
@Override
public void run() {
count++;
myView.setRotation(myView.getRotation() + size);
if(count == 10){
myHandler.removeCallBack(runnable );
}
myHandler.postDelayed(this, 1000); // 1000 means 1 second duration
}
};
myHandler.postDelayed(runnable, 180); // 180 is the delay after new runnable is going to called
}
如何循环自身,这意味着一个代码行,或者一个语句再次调用该事件。一些例子:
void nothing(int a){
if(a> 0)
nothing(a-1);
}
并且不打电话(10)。这就是全部,并避免采取以下行动:
void nothing(int a){
for(int i =0; i< a;i++)
nothing(a-1); //BIG WRONG
}
Do you know your solution?
答案 1 :(得分:-1)
在你的for循环中,你不断用180增加myView的旋转。
如果for循环中的迭代次数可以用2整除,那么得到的旋转将与开头的旋转相同。这就是为什么如果你旋转一次形状,它会被翻转,你可以看到新的旋转,但如果你再次旋转它,它会被翻转。
插图:
没有翻转。轮换:0
#
#
# #
一个翻转。轮换:180
# #
#
#
两次翻转。轮换:360
#
#
# #
以您希望的方式修复代码:
public void rotateImage(final View myView, final int size) {
myHandler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
// include one of the following:
// Way #1: supports animation more easily
for (int i = 0; i < size; i++) {
myView.setRotation(myView.getRotation() + 1);
}
// Way #2: more performant way of doing it
myView.setRotation(myView.getRotation() + size);
}
};
myHandler.postDelayed(runnable, 180);
}