반응형
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | package com.example.test; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends Activity { ArrayList<Vertex> arVertex; private MyView vw; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); vw = new MyView(this); setContentView(vw); arVertex = new ArrayList<Vertex>(); } // 정점 하나의 정보 public class Vertex { float x, y; Boolean Draw; // 생성자 Vertex(float ax, float ay, boolean ad) { x = ax; y = ay; Draw = ad; } } 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); } // 모든 정점을 이어준다. public void onDraw(Canvas canvas) { canvas.drawColor(0xffe0e0e0); // i - 1번째 정점과 i벉 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); } } } // 오버라이딩을 통해 onTouchEvent를 재정의 해준다. public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { Toast.makeText(MainActivity.this, "touch down", Toast.LENGTH_SHORT).show(); arVertex.add(new Vertex(event.getX(), event.getY(), false)); return true; } if (event.getAction() == MotionEvent.ACTION_MOVE) { Toast.makeText(MainActivity.this, "touch move", Toast.LENGTH_SHORT).show(); arVertex.add(new Vertex(event.getX(), event.getY(), true)); invalidate(); //invalidate가 호출되면 전체 뷰의 무효화 처리를 하게되고 다시 onDraw를 통해 새로이 그리게 된다. return true; } return false; } } } /* 출처 : 안드로이드 프로그래밍 정복 세트, 한빛미디어 */ | cs |
반응형
'Basic > Android' 카테고리의 다른 글
Doxygen 사용 방법 및 환경 설정 (0) | 2019.09.16 |
---|---|
안드로이드 어댑터 뷰(Adapter View) (0) | 2019.09.12 |
안드로이드 툴바 만들기 (0) | 2019.09.03 |
안드로이드 스레드, 루퍼, 핸들러, 메시지 큐 (0) | 2019.09.02 |
익명 클래스 예제 (0) | 2019.08.30 |