我想写一个简单的概念验证应用程序,允许用户旋转时钟分针。我很难为OnTouchEvent提供正确的逻辑。在Android时钟移动分钟手
到目前为止,我有以下代码:
public boolean onTouchEvent(MotionEvent e) {
float x = e.getX();
float y = e.getY();
switch (e.getAction()) {
case MotionEvent.ACTION_MOVE:
//find an approximate angle between them.
float dx = x-cx;
float dy = y-cy;
double a=Math.atan2(dy,dx);
this.degree = Math.toDegrees(a);
this.invalidate();
}
return true;
}
protected void onDraw(Canvas canvas) {
super .onDraw(canvas);
boolean changed = mChanged;
if (changed) {
mChanged = false;
}
int availableWidth = getRight() - getLeft();
int availableHeight = getBottom() - getTop();
int x = availableWidth/2;
int y = availableHeight/2;
cx = x;
cy = y;
final Drawable dial = mDial;
int w = dial.getIntrinsicWidth() + 100;
int h = dial.getIntrinsicHeight() + 100;
boolean scaled = false;
if (availableWidth < w || availableHeight < h) {
scaled = true;
float scale = Math.min((float) availableWidth/(float) w, (float) availableHeight/(float) h);
canvas.save();
canvas.scale(scale, scale, x, y);
}
if (changed)
{
dial.setBounds(x - (w/2), y - (h/2), x + (w/2), y + (h/2));
}
dial.draw(canvas);
canvas.save();
float hour = mHour/12.0f * 360.0f;
canvas.rotate(hour, x, y);
final Drawable hourHand = mHourHand;
if (changed) {
w = hourHand.getIntrinsicWidth() + 30;
h = hourHand.getIntrinsicHeight() + 30;
hourHand.setBounds(x - (w/2), y - (h/2), x + (w/2), y + (h/2));
}
hourHand.draw(canvas);
canvas.restore();
canvas.save();
float minute = mMinutes/60.0f * 360.0f;
if (bearing == 0)
{
canvas.rotate(minute, x, y);
}
else
{
canvas.rotate((float)bearing, x, y);
}
final Drawable minuteHand = mMinuteHand;
if (changed) {
w = minuteHand.getIntrinsicWidth() + 30;
h = minuteHand.getIntrinsicHeight() + 30;
minuteHand.setBounds(x - w, y - h, x + w, y + h);
}
minuteHand.draw(canvas);
canvas.restore();
if (scaled) {
canvas.restore();
}
}
然后此基础上,我的OnDraw方法旋转分针到指定的“this.degree”(只是调用canvas.rotate)。我假设我的数学不在这里。我试图按照这里的例子:Calculate angle for rotation in Pie Chart,但这仍然没有正确旋转分针。任何帮助,将不胜感激。
谢谢。我会仔细检查我的中心点。我认为问题是中心点是相对于整个屏幕而不是时钟。所以它就像240,240一样。这可能是真正的问题。思考? – bek
@ user968322我已经添加了一些关于旋转中心的更多细节 – JesusFreke
尝试了所有,仍然没有运气。它开始移动到随机方向。更新了我的文章中的原始代码。 – bek