모바일/android

[안드로이드프로그래밍6판] 직접 풀어보기 9-1, 9-2, 실습 9-1

2021. 12. 15. 14:10
728x90
반응형

참고. 모두 그대로 베꼈으므로 재복습 필요!

 

1. 직접 풀어보기

1) (기초) 9-1


<실행 화면 및 메인 코드>

더보기
실행 화면

package com.cookandroid.myself9_1;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Switch;

public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MyGraphicView(this));
    }

    private static class MyGraphicView extends View {

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

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            Paint paint = new Paint();
            paint.setAntiAlias(true);
            paint.setStrokeWidth(50);
            canvas.drawLine(50, 50,  600, 50, paint);

            paint.setStrokeCap(Paint.Cap.ROUND);
            canvas.drawLine(50, 150, 600, 150, paint);

            RectF rectF = new RectF();
            rectF.set(100, 200, 100 + 400, 100 +200);
            canvas.drawOval(rectF, paint);

            rectF.set(100, 300, 100 + 200, 300+200);
            canvas.drawArc(rectF, 40, 110, true, paint);

            paint.setColor(Color.BLUE);
            rectF.set(100, 600, 300, 600 + 200);
            canvas.drawRect(rectF, paint);

            paint.setColor(Color.argb(0x88, 0xff, 0x00, 0x00));
            rectF.set(150, 650, 350, 850);
            canvas.drawRect(rectF, paint);
        }
    }
}

 

 a. paint.setAntiAlias() - 직선/곡선 좀 더 매끄럽게 만드는 그냥 기본처럼 넣는 문장.

 

 

 

2) (직사각형) 9-2 > 실습 9-1 응용

 

실행 화면
초기 화면 사각형(빨강) 사각형(초록) 사각형(파랑)

 

<메인 코드>

- 원과 달리 직사각형은 객체를 만들고 컨버스와 연결시켜야 함.

- 서브 메뉴 추가

package com.cookandroid.myself9_2;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SubMenu;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    final static int LINE = 1, CIRCLE = 2, RECT = 3;
    static int curShape = LINE;
    static int curColor = Color.DKGRAY;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MyGraphicView(this));
        setTitle("간단 그림판(개선)");
    }
    private class MyGraphicView extends View {
        int startX = -1, startY = -1, stopX = -1, stopY =-1;
        public MyGraphicView(Context context) {
            super(context);
        }
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    startX = (int) event.getX();
                    startY = (int) event.getY();
                    break;
                case MotionEvent.ACTION_MOVE:
                case MotionEvent.ACTION_UP:
                    stopX = (int) event.getX();
                    stopY = (int) event.getY();
                    this.invalidate();
                    break;
            } return true;
        }
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            Paint paint = new Paint();
            paint.setAntiAlias(true);
            paint.setStrokeWidth(5);
            paint.setStyle(Paint.Style.STROKE);
            paint.setColor(curColor);

            switch (curShape) {
                case LINE:
                    canvas.drawLine(startX, startY, stopX, stopY, paint);
                    break;
                case CIRCLE:
                    //지름 = 점과 점 사이 길이
                    int radius = (int) Math.sqrt(Math.pow(stopX - startX, 2)
                            + Math.pow(stopY - startY, 2));
                    canvas.drawCircle(startX, startY, radius, paint);
                    break;
                case RECT:
                    //직사각형 객체 만들기
                    Rect rect = new Rect(startX, startY, stopX, stopY);
                    canvas.drawRect(rect, paint);
                    break;
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, 1, 0, "선 그리기");
        menu.add(0, 2, 0, "원 그리기");
        menu.add(0, 3, 0, "사각형 그리기");
        SubMenu subMenu = menu.addSubMenu("색상 변경 >>");
        subMenu.add(0, 4, 0, "빨강");
        subMenu.add(0, 5, 0, "초록");
        subMenu.add(0, 6, 0, "파랑");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case 1:
                curShape = LINE;
                break;
            case 2:
                curShape = CIRCLE;
                break;
            case 3:
                curShape = RECT;
                break;
            case 4:
                curColor = Color.RED;
                break;
            case 5:
                curColor = Color.GREEN;
                break;
            case 6:
                curColor = Color.BLUE;
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}

 

2. 실습 9-1

실행 화면
초기 화면 선 그리기 원 그리기

 

<메인 코드>

- 원을 그릴때, 반지름을 요구함. 이때 점과 점사이의 거리를 활용해 구한다.

package com.cookandroid.practice9_1;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    final static int LINE = 1, CIRCLE = 2;
    static int curShape = LINE;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MyGraphicView(this));
        setTitle("간단 그림판");
    }
    private static class MyGraphicView extends View {
        int startX = -1, startY = -1, stopX = -1, stopY = -1;
        public MyGraphicView(Context context) {
            super(context);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    startX = (int) event.getX();
                    startY = (int) event.getY();
                    break;
                case MotionEvent.ACTION_MOVE:
                case MotionEvent.ACTION_UP:
                    stopX = (int) event.getX();
                    stopY = (int) event.getY();
                    //화면 무효화, on Draw 메소드 자동실행
                    this.invalidate();
                    break;
            } return true;
        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            Paint paint = new Paint();
            paint.setAntiAlias(true);
            paint.setStrokeWidth(5);
            paint.setStyle(Paint.Style.STROKE);
            paint.setColor(Color.RED);

            switch (curShape) {
                case LINE:
                    canvas.drawLine(startX, startY, stopX, stopY, paint);
                    break;
                case CIRCLE:
                    //지름 = 점과 점 사이 길이
                    int radius = (int) Math.sqrt(Math.pow(stopX - startX, 2)
                            +Math.pow(stopY-startY, 2));
                    canvas.drawCircle(startX, startY, radius, paint);
                    break;
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, 1, 0, "선 그리기");
        menu.add(0, 2, 0, "원 그리기");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case 1:
                curShape = LINE;
                return true;
            case 2:
                curShape = CIRCLE;
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
저작자표시 비영리 변경금지 (새창열림)

'모바일 > android' 카테고리의 다른 글

[안드로이드프로그래밍6판] 명시적 인텐트 개념과 예제  (0) 2021.12.15
[안드로이드프로그래밍6판] 그림판 응용  (0) 2021.12.15
[안드로이드프로그래밍6판] (대화 상자) 실습 7-3, 직접 풀어보기 7-3  (0) 2021.12.11
[안드로이드프로그래밍6판] (컨텍스트 메뉴) 실습 7-2, 직접 풀어보기 7-2  (0) 2021.10.22
[안드로이드프로그래밍6판] (옵션 메뉴)실습 7-1 고대로 베낌, 직접 풀어보기 7-1  (0) 2021.10.22
'모바일/android' 카테고리의 다른 글
  • [안드로이드프로그래밍6판] 명시적 인텐트 개념과 예제
  • [안드로이드프로그래밍6판] 그림판 응용
  • [안드로이드프로그래밍6판] (대화 상자) 실습 7-3, 직접 풀어보기 7-3
  • [안드로이드프로그래밍6판] (컨텍스트 메뉴) 실습 7-2, 직접 풀어보기 7-2
hatch
hatch
250x250
hatch
차근차근 쌓아올리는,
hatch
전체
오늘
어제
  • 분류 전체보기 (121)
    • TIL (3)
    • [JAVA] (17)
      • 생활코딩 (11)
    • 모바일 (25)
      • android (24)
      • ReactNative (1)
    • 웹개발 (25)
      • React (3)
      • jQuery (5)
      • Springboot (2)
    • 알고리즘 (42)
    • [프로그래밍기초지식] (1)
    • [기술문서 읽기] (0)
      • 개념 번역 (0)
    • 인사이트(insight) (2)
    • git (2)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • write
  • manger

공지사항

인기 글

태그

  • DP
  • 중복리니어레이아웃
  • 210908
  • 모프2주차
  • 백준
  • 명시적 인텐트
  • javascript
  • scanf
  • 타일링
  • TIL
  • 별찍기
  • 깊은복사
  • state
  • jquery
  • 안드로이드프로그래밍6판
  • 반복문
  • 재귀
  • 노이클립스
  • Doit!자바프로그래밍입문
  • BufferedReader

최근 댓글

최근 글

hELLO · Designed By 정상우.
hatch
[안드로이드프로그래밍6판] 직접 풀어보기 9-1, 9-2, 실습 9-1
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.