在基于触摸事件的情况下,是否可以沿着圆形路径移动和旋转图像,如下所示:
我查看了这个问题:
在Android中基于触摸事件将图像移动到圆形运动
但它只告诉我如何沿着圆形移动图像,而不是旋转它。
![enter image description here](https://istack.dev59.com/PPL3d.webp)
更新:完整示例已发布在GitHub上,网址为https://github.com/jselbie/xkcdclock
每次触摸事件发生时,请获取触摸点的x、y坐标,并计算相对于位图中心的旋转角度。使用该值来确定要绘制的位图需要旋转多少。
首先,假设一个逻辑坐标系,其中您元素的中心点在x、y空间中的位置为(0,0)。
因此,任何相对于中心的触摸点之间的角度(以度为单位)可以计算如下:
double ComputeAngle(float x, float y)
{
final double RADS_TO_DEGREES = 360 / (java.lang.Math.PI*2);
double result = java.lang.Math.atan2(y,x) * RADS_TO_DEGREES;
if (result < 0)
{
result = 360 + result;
}
return result;
}
float _refX; // x coordinate of last touch event
float _refY; // y coordinate or last touch event
float _rotation; // what angle should the source image be rotated at
float _centerX; // the actual center coordinate of the canvas we are drawing on
float _centerY; // the actual center coordinate of the canvas we are drawing on
boolean onTouch(View v, MotionEvent event)
{
int action = event.getAction();
int actionmasked = event.getActionMasked();
if (!_initialized)
{
// if we haven't computed _centerX and _centerY yet, just bail
return false;
}
if (actionmasked == MotionEvent.ACTION_DOWN)
{
_refX = event.getX();
_refY = event.getY();
return true;
}
else if (actionmasked == MotionEvent.ACTION_MOVE)
{
// normalize our touch event's X and Y coordinates to be relative to the center coordinate
float x = event.getX() - _centerX;
float y = _centerY - event.getY();
if ((x != 0) && (y != 0))
{
double angleB = ComputeAngle(x, y);
x = _refX - _centerX;
y = _centerY - _refY;
double angleA = ComputeAngle(x,y);
_rotation += (float)(angleA - angleB);
this.invalidate(); // tell the view to redraw itself
}
}
本文中有一些细节没有说明,例如如何绘制实际的位图。你可能还希望处理ACTION_UP和ACTION_CANCEL事件,以将_rotation规范化为始终在0到360之间。但是主要的点是上述代码是计算Bitmap应该在View上绘制的_rotation的框架。类似以下内容:
void DrawBitmapInCenter(Bitmap bmp, float scale, float rotation, Canvas canvas)
{
canvas.save();
canvas.translate(canvas.getWidth()/2, canvas.getHeight()/2);
canvas.scale(scale, scale);
canvas.rotate(rotation);
canvas.translate(-bmp.getWidth()/2, -bmp.getHeight()/2);
canvas.drawBitmap(bmp, 0, 0, _paint);
canvas.restore();
}