我想寫一個簡單的概念驗證應用程序,允許用戶旋轉時鐘分針。我很難爲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