2012-11-19 5 views

답변

1

안녕하세요 당신은 아래 코드를 참조 할 수 있습니다. onTouchEvent에서 방향을 처리하고 객체를 이동할 수 있습니다.

// Tutorial2D.java 주요 활동

import android.app.Activity; 
import android.graphics.Color; 
import android.os.Bundle; 
import android.view.Window; 

public class Tutorial2D extends Activity { 
    Square drawView; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     requestWindowFeature(Window.FEATURE_NO_TITLE); 
     drawView = new Square(this); 
     drawView.setBackgroundColor(Color.WHITE); 
     setContentView(drawView); 
    } 

} 

// Square.java

import android.content.Context; 
import android.graphics.Bitmap; 
import android.graphics.Canvas; 
import android.graphics.Color; 
import android.graphics.Paint; 
import android.view.MotionEvent; 
import android.view.View; 

class Square extends View { 
    Bitmap mBitmap; 
    Paint paint = new Paint(); 

    public Square(Context context) { 
     super(context); 
    } 

    @Override 
    public void onDraw(Canvas canvas) { 
     canvas.rotate(direction, mCenterX, mCenterY); 
     paint.setColor(Color.BLACK); 
     paint.setStrokeWidth(3); 
     canvas.drawRect(230, 230, 280, 280, paint); 
     paint.setStrokeWidth(0); 
     paint.setColor(Color.CYAN); 
     canvas.drawRect(233, 260, 277, 277, paint); 
     paint.setColor(Color.YELLOW); 
     canvas.drawRect(233, 233, 277, 260, paint); 
    } 

    private float mCenterX, mCenterY; 
    private float direction = 0; 
    private float sX, sY; 
    private float startDirection = 0; 

    private void touchStart(float x, float y) { 
     mCenterX = this.getWidth()/2; 
     mCenterY = this.getHeight()/2; 
     sX = x; 
     sY = y; 
    } 

    private void touchMove(float x, float y) { 
     // this calculate the angle the image rotate 
     float angle = (float) angleBetween2Lines(mCenterX, mCenterY, sX, sY, x, 
       y); 
     direction = (float) Math.toDegrees(angle) * -1 + startDirection; 
     this.invalidate(); 
    } 

    @Override 
    public boolean onTouchEvent(MotionEvent event) { 

     float x = event.getX(); 
     float y = event.getY(); 
     switch (event.getAction()) { 
     case MotionEvent.ACTION_DOWN: 
      // record the start position of finger 
      touchStart(x, y); 
      break; 
     case MotionEvent.ACTION_MOVE: 
      // update image angle 
      touchMove(x, y); 
      break; 
     case MotionEvent.ACTION_UP: 
      startDirection = direction; 
      break; 
     } 

     return true; 
    } 

    public double angleBetween2Lines(float centerX, float centerY, float x1, 
      float y1, float x2, float y2) { 
     double angle1 = Math.atan2(y1 - centerY, x1 - centerX); 
     double angle2 = Math.atan2(y2 - centerY, x2 - centerX); 
     return angle1 - angle2; 
    } 
} 
0

실제 응용 프로그램이 무엇인지에 따라 달라지기 때문에 대답하기가 어렵습니다. 어쩌면 ImageView와 같은 작은 구성 요소에서 "그림"을 만들고 그 다음에 애니메이션을 사용하여 ImageView를 움직이는 것이 가장 적합 할 수도 있습니다. 그렇지 않은 경우 캔버스를 다시 칠할 필요가 있습니다.