【问题标题】:Rotate canvas along its center based on user touch - Android根据用户触摸沿其中心旋转画布 - Android
【发布时间】:2011-10-26 08:17:11
【问题描述】:

我想根据用户的触摸在画布的中心轴上循环旋转。

就像一个旧的电话拨号器。

我想基于中心旋转

但是

现在它基于左上角旋转。所以我只能看到图像旋转的 1/4。

我试过如下

onDraw(Canvas canvas){
  canvas.save();
  // do my rotation
  canvas.rotate(rotation,0,0);
  canvas.drawBitmap( ((BitmapDrawable)d).getBitmap(),0,0,p );
  canvas.restore();
}

@Override
        public boolean onTouchEvent(MotionEvent e) {
                  float x = e.getX();
              float y = e.getY();
              updateRotation(x,y);
              mPreviousX = x;
              mPreviousY = y;
            invalidate();
        }

  private void updateRotation(float x, float y) {

          double r = Math.atan2(x - centerX, centerY - y);
            rotation = (int) Math.toDegrees(r);
        }

【问题讨论】:

  • 当前输出是什么?
  • 我想基于中心旋转,但它基于左上角旋转。所以我只能看到图像旋转的 1/4。
  • 您的问题在这里得到解答:stackoverflow.com/questions/4166917/…

标签: android rotation touch android-canvas


【解决方案1】:

您需要将此添加到您的自定义视图方法中

@Override     
public void onSizeChanged (int w, int h, int oldw, int oldh){ 
  super.onSizeChanged(w, h, oldw, oldh);         

  screenW = w;         
  screenH = h; 
}

这个方法会给你画布大小然后使用

canvas.rotate(rotation, screenW / 2, screenH / 2);

【讨论】:

  • +1 回答。谢谢我之前离开的这个 onSizeChanged 方法。现在它工作得很好。
  • 很好,如果您需要旋转不在画布中心的图像,则只需输入图像的中心作为枢轴旋转坐标
【解决方案2】:

通过旋转点来旋转api:

canvas.rotate(rotation, 0, centerY);

【讨论】:

  • 感谢 +1 的回答,但 canvas.rotate(rotation,0,centerY) 只给了我半边(右半旋转),但 canvas.rotate(rotation,centerX,centerY) 给了我精确的圆形中点旋转。
【解决方案3】:

您可以使用而不是旋转画布 x=0;

x=x+50;
yourview.setRotation(x);

在触摸事件和 x=x-50 用于旋转倒序词

我认为这会有所帮助

【讨论】:

    猜你喜欢
    • 2018-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多