본문 바로가기

Android

입력 - 터치 실습

package com.example.testex20;

 

import java.util.ArrayList;

 

import android.os.Bundle;

import android.R.color;

import android.app.Activity;

import android.content.Context;

import android.graphics.Canvas;

import android.graphics.Color;

import android.graphics.Paint;

import android.view.Menu;

import android.view.MotionEvent;

import android.view.View;

 

public class MainActivity extends Activity {

    

     private MyView vw;

     ArrayList<Vertex>arVertex;

    

     @Override

     public void onCreate(Bundle savedInstanceState) {

           super.onCreate(savedInstanceState);

           vw = new MyView(this);

           setContentView(vw);

           arVertex = new ArrayList<Vertex>();      

     }

    

     //정점 하나에 대한 정보를 가지는 클래스

    

     public class Vertex{

           Vertex(float ax, float ay, boolean ad){

                x=ax;

                y=ay;

                Draw=ad;

           }

           float x;

           float y;

           boolean Draw;

     }

    

     protected class MyView extends View{

           Paint mPaint;

           public MyView(Context context){

                super(context);

                //Paint 객체 미리 초기화

                mPaint= new Paint();

                mPaint.setColor(Color.BLACK);

                mPaint.setStrokeWidth(3);

                mPaint.setAntiAlias(true);

           }

          

           @Override

           public void onDraw(Canvas canvas){

                canvas.drawColor(Color.LTGRAY);

                //정점을 순회하면서 선분으로 잇는다.

                for(int i=0; i<arVertex.size(); i++){

                     if(arVertex.get(i).Draw){

                           canvas.drawLine(arVertex.get(i-1).x, arVertex.get(i-1).y, arVertex.get(i).x, arVertex.get(i).y, mPaint);

                     }

                }

           }

          

           //터치를 이동시마다 정점들을 추가한다.

           @Override

           public boolean onTouchEvent(MotionEvent event){

                if(event.getAction() == MotionEvent.ACTION_DOWN){

                     arVertex.add(new Vertex(event.getX(), event.getY(), false));

                     return true;

                }

               

                if(event.getAction() == MotionEvent.ACTION_MOVE){

                     arVertex.add(new Vertex(event.getX(), event.getY(), true));

                     invalidate();

                     return true;

                }

                return false;

           }

          

     }

    

}

 

 

 



손가락으로 화면을 터치하여 곡선을 그릴 수 있다

'Android' 카테고리의 다른 글

텍스트뷰(textview) - 기본속성  (0) 2013.03.28
이벤트 예제 - 클릭  (1) 2013.03.28
입력 - 터치(touch)  (0) 2013.03.28
이벤트 처리 - 리스너 인터페이스 구현  (0) 2013.03.27
이벤트 처리 - 콜백 메서드 재정의  (0) 2013.03.27