CHAP 8. 그래픽.

Slides:



Advertisements
Similar presentations
5-3. 세이더 천안천일고등학교 류빈 1.Canvas 와 Paint 객체를 통해 화면에 원하는 도형을 그리고 속성을 변경하는 기본적인 방법에 대해 소개 한다. 2. 토스트로 메시지를 출력하는 방법과 스피커를 통해 소리를 출력하는 방법에.
Advertisements

1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
Ch 7. Spring EL (Spring Framework 3.0 M3) 백기선
Graphics with Canvas, SurfaceView, and multitouch processing (panning and multitouch zoom) GraphicsWithCanvas_2012.pptx.
Graphics.  2D Graphics using  ImageView  Canvas  ViewAnimation.
Basic 2D Graphics in Android. Android Graphics Programming There are many ways to do graphics programming in Android – 2D vs. 3D – static vs. dynamic.
Camera. Make new project – Give permission to use camera Make button called TakePicture Make button called ShowLastPic Add SurfaceView to layout – Surface.
Application Fundamentals. See: developer.android.com/guide/developing/building/index.html.
User Interface Android Applications. Activities An activity presents a visual user interface. Each activity is given a default window to draw in. The.
Android Form Elements. Views Provide common UI functionality Form elements: text area, button, radio button, checkbox, dropdown list, etc. Date and time.
My own View Android development Maarten Pennings 2011 oct 14.
Crash Course in Android Development. 2 Content  Installing the ADT  Hardware and OS requirements  Java  ADT Bundle  Eclipse Project Setup  Drawing.
2D Graphics: Part 1. Android Graphics Libraries 2D Graphics –custom 2D graphics library in packages android.graphics android.graphics.drawable android.graphics.drawable.shapes.
@2011 Mihail L. Sichitiu1 Android Introduction Hello World.
Custom Views, Drawing, Styles, Themes, ViewProperties, Animations, oh my!
Android Application Development Tutorial. Topics Lecture 5 Overview Overview of Networking Programming Tutorial 2: Downloading from the Internet.
Basic Drawing Techniques
2D Graphics: Part 2.
4 출 력.
6-2 2D Graphics CSNB544 Mobile Application Development Thanks to Utexas Austin.
Android Tutorial Team 3 Jerry Yu Mayank Mandava Mu Du Will Wangles.
CHAP 10. 고급 위젯. © 2012 생능출판사 All rights reserved 어댑터 뷰 어댑터 뷰 (AdapterView) 는 배열이나 파일, 데이터 베이스에 저장된 데이터를 화면에 표시할 때 유용한 뷰.
8-3. 버튼 천안천일고등학교 류빈. 1. 가장 기본적인 위젯인 TextView 를 통해 위젯의 일반 적인 특징과 프로그래밍 방법을 상세하게 연구해보고 버튼의 사용 방법을 익힌다. 학습목표 1. 리소스 2. 텍스트 뷰 3. 버튼 학습내용 2.
2012 내장형 시스템 설계  Full Color LED 디바이스 구성  Full Color LED 디바이스 드라이버  Full Color LED JNI 라이브러리 작성  Full Color LED 안드로이드 App 구현  JNI 라이브러리.
1/29/ Android Programming: FrameLayout By Dr. Ramji M. Makwana Professor and Head, Computer Engineering Department A.D. Patel.
Import import android.graphics.Bitmap; import android.widget.ImageView;
Android Graphics Library. Color Android colors are represented with four numbers, one each for alpha, red, green, and blue (ARGB). Each component can.
로봇 모니터링 1/2 UNIT 20 로봇 SW 콘텐츠 교육원 조용수. 학습 목표 Message Queue Handler 2.
5-1. 캔버스 천안천일고등학교 류빈 1.Canvas 와 Paint 객체를 통해 화면에 원하는 도형을 그리고 속성을 변경하는 기본적인 방법에 대해 소개 한다. 2. 토스트로 메시지를 출력하는 방법과 스피커를 통해 소리를 출력하는 방법에.
Custom Widget 1 UNIT 26 로봇 SW 콘텐츠 교육원 조용수. 캔버스 public void drawColor(int color) 2 public class ControllerView extends View { public ControllerView(Context.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Introduction to Android (Part.
Ch3. 캔버스 활용 3-2 도형으로 안드로이드 캐릭터 만들기.
1 Introducing Activity and Intent. 2 Memory LinearLayout, weight=2 LinearLayout, weight=1 TextView ListView.
ANDROID – DRAWING IMAGES – SIMPLE EXAMPLE IN INTERFACE AND EVENT HANDLING L. Grewe.
Announcements Homework #2 will be posted after class due Thursday Feb 7, 1:30pm you may work with one other person No office hours tonight (sorry!) I will.
Mobile Device Development Camera and Sensors Dr.YingLiang Ma.
Cosc 5/4730 Android drawing. Screen support Android is the OS and is used a many different hardware created by different vendors. – Screen size For simplicity,
Android Using Menus Notes are based on: The Busy Coder's Guide to Android Development by Mark L. Murphy Copyright © CommonsWare, LLC. ISBN:
Android Threads. Threads Android will show an “ANR” error if a View does not return from handling an event within 5 seconds Or, if some code running in.
CHAP 11. 액티비티와 인텐트.
CHAP 8. 고급 그래픽과 O PEN GL. © 2012 생능출판사 All rights reserved C ANVAS 클래스와 P AINT 클래스.
목차 한국기술교육대학교 강사: 김 영 준 ㈜헬로앱스 1일차 아두이노 제어 실습
Android and s Ken Nguyen Clayton state University 2012.
아주대학교 LifecareScienceLAB Android Seminar 3 rd class Android Software Development 2011/05/04 – p.m. 06:00 – 팔달관 409 호 아주대학교.
Custom Widget 2 UNIT 27 로봇 SW 콘텐츠 교육원 조용수. 학습 목표 Custom Widget –Canvas 를 이용하여 Custom Widget 을 만든다. 2.
실전 이미지 처리 프로그래밍 Lecture #10. 강의 목차 ▶ 실제 게임을 구현하는 데 필요한 화면 구성을 알아본다. ▶ Canvas 클래스와 Graphics 클래스를 이용해 가장 기본적인 게임 화면을 하나씩 직접 구현해 본다. 2Mobile Programming.
Mobile Computing Lecture#12 Graphics & Animation.
CHAP 14. 프로세스와 스레드. © 2012 생능출판사 All rights reserved 다중 스레딩 하나의 애플리케이션이 동시에 여러 가지 작업을 하 는 것 이들 작업은 스레드 (thread) 라고 불린다.
CHAP 6. 이벤트 처리. © 2012 생능출판사 All rights reserved 폴링과 이벤트 구동 방식.
CHAP 7. 메뉴와 대화상자. © 2012 생능출판사 All rights reserved 메뉴의 종류 옵션 메뉴 : 사용자가 MENU 키를 누를 때 나타난다. 컨텍스트 메뉴 : 컨텍스트 메뉴는 사용자가 화면을 일정 시간 이상으로 길게 누르면 나타나는 메뉴이다.
아주대학교 LifecareScienceLAB Android Seminar 2 nd class Android Software Development 2011/04/13 – p.m. 06:00 – 팔달관 409 호 아주대학교.
Basic 2D Graphics in Android. Android Graphics Programming There are many ways to do graphics programming in Android – 2D vs. 3D – static vs. dynamic.
© 2012 생능출판사 All rights reserved CHAP 8. 그래픽. © 2012 생능출판사 All rights reserved 안드로이드에서의 2 차원 그래픽 사용 방법 1) XML 파일로 그래픽이나 애니메이션을 정의한다. 그리는 작업은 안드로이드 시스템이.
David Sutton 2D GRAPHICS IN ANDROID. INTRODUCTION AND OUTLINE  In this week’s session we will create a simple Kaleidoscope application. Topics that will.
CHAP 8. 그래픽. © 2012 생능출판사 All rights reserved 안드로이드에서의 그래픽 XML 파일로 그래픽이나 애니메이션을 정의한다. 그 리는 작업은 안드로이드 시스템이 담당한다. onDraw() 메소드 안에 draw...() 와 같은 메소드를 호.
Android Application 2D Graphics cs.
Lecture 3: Animation & Graphics
Android Introduction Hello World
GUI Programming Fundamentals
滑動版面 建國科技大學 資管系 饒瑞佶 2013/7 V1.
CS499 – Mobile Application Development
Android Introduction Hello World.
2D Graphics: Part 2.
תכנות ב android אליהו חלסצ'י.
Android Programming Lecture 6
null, true, and false are also reserved.
Graphics with Canvas.
Cannon Game App Android How to Program
BMI Android Application will take weight and height from the users to calculate Body Mass Index (BMI) with the information, whether user is underweight,
CIS 470 Mobile App Development
Presentation transcript:

CHAP 8. 그래픽

안드로이드에서의 그래픽 XML 파일로 그래픽이나 애니메이션을 정의한다. 그 리는 작업은 안드로이드 시스템이 담당한다. onDraw() 메소드 안에 draw...()와 같은 메소드를 호 출하여 직접 그린다.

커스텀 뷰를 사용하여 그리기 ... class MyView extends View { public MyView(Context context) { super(context); setBackgroundColor(Color.YELLOW); } @Override protected void onDraw(Canvas canvas) { Paint paint = new Paint(); paint.setColor(Color.RED); canvas.drawLine(20, 50, 100, 50, paint); canvas.drawRect(10, 110, 100, 150, paint); canvas.drawCircle(50, 200, 30, paint); canvas.drawText("텍스트도 그릴 수 있습니다", 10, 300, paint);

커스텀 뷰를 사용하여 그리기 public class GraphicsActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MyView w = new MyView(this); setContentView(w); }

Canvas 클래스와 Paint 클래스 Canvas 클래스는 그림을 그리는 캔버스(화포)에 해 당

몇 개의 기초 도형 그리기 ... @Override protected void onDraw(Canvas canvas) { Paint paint = new Paint(); paint.setColor(Color.YELLOW); canvas.drawColor(Color.BLUE); canvas.drawRoundRect(new RectF(10,10,110,110), 5, 5, paint); canvas.drawOval(new RectF(150,10,250,110), paint); paint.setColor(Color.RED); canvas.drawArc(new RectF(10,120,110,220), 120, 270, true, paint); float[] pts={ 10, 250, 100, 270, 100, 270, 20, 290, 20, 290, 120, 300}; canvas.drawLines(pts, paint); }

커스텀 뷰를 XML에서 참조하기 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <kr.co.company.graphiccustomview.CustomView android:layout_height="fill_parent" /> </LinearLayout>

커스텀 뷰를 XML에서 참조하기 ... public class CustomView extends View { public CustomView(Context context) { super(context); setBackgroundColor(Color.YELLOW); } public CustomView(Context context, AttributeSet attrs) { @Override protected void onDraw(Canvas canvas) { Paint paint = new Paint(); paint.setColor(Color.RED); canvas.drawArc(new RectF(10, 120, 110, 220), 120, 270, true, paint);

색상 색의 3원색인 Red, Green, Blue 성분을 8비트로 표 시 paint.setColor(0xFF0000); paint.setColor(Color.RED);

선의 스타일 FILL 도형의 내부를 채운다. FILL_AND_STROKE 도형의 내부를 채우면서 외곽선도 그린다. STROKE 도형의 외곽선만 그린다.

원호그리기 class MyView extends View { private Paint mPaints, mFramePaint;         private RectF mBigOval;         private float mStart, mSweep;         private static final float SWEEP_INC = 2;         private static final float START_INC = 15;         public MyView(Contextcontext) {                super(context);                mPaints = new Paint();                mPaints.setAntiAlias(true);                mPaints.setStyle(Paint.Style.FILL);                mPaints.setColor(0x88FF0000);               mFramePaint = new Paint();                mFramePaint.setAntiAlias(true);                mFramePaint.setStyle(Paint.Style.STROKE);               mFramePaint.setStrokeWidth(3);                mFramePaint.setColor(0x8800FF00);                mBigOval = new RectF(40, 10,280, 250);         }

원호그리기 @Override protected void onDraw(Canvas canvas) {                canvas.drawColor(Color.YELLOW);                canvas.drawRect(mBigOval, mFramePaint);                canvas.drawArc(mBigOval, mStart, mSweep, false, mPaints);                mSweep += SWEEP_INC;                if (mSweep >360) {                        mSweep -= 360;                        mStart += START_INC;                        if (mStart >= 360)                               mStart -= 360; }                invalidate();      } public class MyArcActivity extends Activity {         protected void onCreate(BundlesavedInstanceState) {                super.onCreate(savedInstanceState);                setContentView(new MyView(this));        

원호그리기

앤티 에일리어싱 paint.setAntiAlias(true);

폰트 static Typeface create (Typeface family, int style) 메소드 static Typeface create (Typeface family, int style) static Typeface create (String familyName, int style) Typeface 객체는 Typeface 클래스 내부의 create() 메소드로 생성된다. family: 폰트 이름 , DEFAULT, DEFAULT_BOLD, MONOSPACE, SANS_SERIF, SERIF 중의 하나 style: 폰트 스타일, NORMAL, BOLD, ITALIC, BOLD_ITALIC 중의 하나 위의 메소드들은 주어진 폰트와 스타일에 가장 일치하는 Typeface 객체를 생성한다. 이 메소드는 주로 이미 존재하는 폰트로부터 새로운 스타일의 폰트를 생성하고자 할 때 호출한다. 만약 family가 null이면 디폴트 폰트 패밀리를 선택한다. Typeface setTypeface (Typeface typeface) 폰트를 typeface로 변경한다. void drawText(String text, float x, float y, Paint paint) void drawText(String text, int start, int end, float x, float y, Paint paint) void drawText(char[] text, int index, int count, float x, float y, Paint paint) 텍스트를 화면에 그린다.

폰트 예제 ... @Override protected void onDraw(Canvas canvas) { Paint paint = new Paint(); paint.setAntiAlias(true); paint.setTextSize(25); Typeface t; t = Typeface.create(Typeface.DEFAULT, Typeface.NORMAL); paint.setTypeface(t); canvas.drawText("DEFAULT 폰트", 10, 100, paint); t = Typeface.create(Typeface.DEFAULT_BOLD, Typeface.NORMAL); paint.setTypeface(t); canvas.drawText("DEFAULT_BOLD 폰트", 10, 150, paint); t = Typeface.create(Typeface.MONOSPACE, Typeface.NORMAL); canvas.drawText("MONOSPACE 폰트", 10, 200, paint); t = Typeface.create(Typeface.SERIF, Typeface.NORMAL); canvas.drawText("SERIF 폰트", 10, 250, paint); t = Typeface.create(Typeface.SANS_SERIF, Typeface.NORMAL); canvas.drawText("SANS_SERIF 폰트", 10, 300, paint); }

폰트 예제 실행 결과

외부 폰트 사용 폰트 파일을 구하여 프로젝트의 asset 폴더로 복사 @Override protected void onDraw(Canvas canvas) { Typeface myFont; Paint paint = new Paint(); paint.setAntiAlias(true); myFont = Typeface.createFromAsset(getContext().getAssets(), "animeace2_ital.ttf"); paint.setTypeface(myFont); paint.setTextSize(25); canvas.drawText("This is a New Font!!!", 10, 100, paint); canvas.drawText("Have Fun!!!", 10, 200, paint); }

패스 그리기 패스(path)는 복잡한 기하학적인 경로를 표현 패스는 직선과 타원, 곡선으로 이루어질 수 있다 @Override protected void onDraw(Canvas canvas) { Path path = new Path(); Paint paint = new Paint(); paint.setStyle(Paint.Style.STROKE); path.moveTo(20, 100); path.lineTo(100, 200); path.cubicTo(150, 30, 200, 300, 300, 200); paint.setColor(Color.BLUE); canvas.drawPath(path, paint); paint.setStyle(Paint.Style.FILL); paint.setTextSize(50); canvas.drawTextOnPath("This is a test!!", path, 0, 0, paint); }

이미지 표시 리소스 폴더에 이미지 파일를 복사한다. 예를 들어서 android.png 파일을 프로젝트의 res/drawable-mdpi 폴더에 복사 프로그램에서는 R.drawable.android로 참조 지원되는 파일 형식은 PNG (선호), JPG (가능), GIF (권장되지 않음)

이미지 표시하기: ImageView 사용 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent“ android:layout_height="wrap_content" android:text="@string/hello" /> <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:src="@drawable/android" /> </LinearLayout>

코드로 화면에 이미지 표시 class MyView extends View { public MyView(Context context) { super(context); setBackgroundColor(Color.YELLOW); } @Override protected void onDraw(Canvas canvas) { Paint paint = new Paint(); Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.android); canvas.drawBitmap(b, 0, 0, null); public class ImageDispActivity extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MyView w = new MyView(this); setContentView(w);

이미지 크기 변환 변환 행렬 사용 ... Matrix m = new Matrix();m.preScale(1, -1); Bitmap b = BitmapFactory.decodeResource(getResource(), R.drawable.android); Bitmap mb=Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), m, false);

이미지 크기 변환 ... protected void onDraw(Canvas canvas) { Paint paint = new Paint(); Matrix m= new Matrix(); m.preScale(1, -1); Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.house); Bitmap mb = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), m, false); Bitmap sb = Bitmap.createScaledBitmap(b, 200, 200, false); canvas.drawBitmap(mb, 0, 0, null); canvas.drawBitmap(sb, 100, 100, null); }

도형 객체 사각형이나 원 같은 도형을 객체로 표시한다. Drawable 객체 XML로 객체를 생성 코드로 객체를 생성

XML로 도형 객체 정의 <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape=["rectangle" | "oval" | "line" | "ring"] > <corners .... /> <gradient .... /> <padding .... /> <size .... /> <solid android:color="color" /> <stroke android:width="integer" .... /> </shape>

XML로 도형 객체 정의: 예제 <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"> <solid android:color="#ff0000"/> </shape>

XML로 도형 객체 정의: 예제 ... LinearLayout mLinearLayout; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mLinearLayout = new LinearLayout(this); ImageView i = new ImageView(this); i.setImageDrawable(R.drawable.oval); i.setMinimumHeight(100); i.setMinimumWidth(100); mLinearLayout.addView(i); setContentView(mLinearLayout); }

에니메이션 프로퍼티 애니메이션(property animation) 뷰 애니메이션(view animation) 모든 객체의 속성을 애니메이션할 수 있다. 뷰 애니메이션(view animation) View 객체만을 애니메이션 드로워블 애니메이션(Drawable animation) 여러 장의 이미지를 사용

프로퍼티 애니메이션 다음과 같은 값들을 설정 가능 지속 시간(duration) 시간 보간(time interpolation): 시간의 함수로 값이 어떻게 변하는지를 정의 반복 횟수와 반복 동작(Repeat count and behavior) 애니메이터 집합(Animator sets): 애니메이션의 집합을 생성할 수 있다. 프레임 재생 지연(Frame refresh delay): 애니메이션을 다시 그리는 횟수를 설정한다.

선형 애니메이션 비선형 애니메이션

프로퍼티 애니메이션 코드

뷰 애니메이션

코드

드로워블 애니메이션 영화 필름처럼 여러 개의 이미지가 순서대로 재생되 어서 생성되는 전통적인 애니메이션

드로워블 애니메이션 애니메이션을 구성하는 프레임들을 나열하는 XML 파일을 생성

서피스 뷰 서피스뷰는 사용자 인터페이스와는 별도로 애플리 케이션에게 그림을 그릴 수 있는 화면을 제공

서피스 뷰의 구조 SurfaceView 클래스를 상속한 뷰를 생성한다. class MyView extends SurfaceView implements SurfaceHolder.Callback { public void surfaceCreated(SurfaceHolder holder) { // 서피스가 준비되었으므로 스레드를 시작한다. ... } public void surfaceDestroyed(SurfaceHolder holder) { // 서피스가 소멸되었으므로 스레드를 종료한다. public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // 서피스가 변경

스레드를 정의한다. class MyThread extends Thread { SurfaceHolder holder; ... public void run() { canvas = holder.lockCanvas(); // 캔버스에 그림을 그린다. holder.unlockCanvasAndPost(canvas); }

서피스 뷰 예제

핵심적인 코드 // 서피스 뷰 정의 public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback { … public MySurfaceView(Context context) { // 생성자 super(context); SurfaceHolder holder = getHolder(); // 서피스 뷰의 홀더를 얻는다. holder.addCallback(this); // 콜백 메소드를 처리한다. thread = new MyThread(holder); // 스레드를 생성한다. // Ball 객체를 생성하여서 배열에 넣는다. for (int i = 0; i < 10; i++) basket[i] = new Ball(20); } public MyThread getThread() { return thread;

핵심적인 코드 public void surfaceCreated(SurfaceHolder holder) { // 스레드를 시작한다. thread.setRunning(true); thread.start(); } public void surfaceDestroyed(SurfaceHolder holder) { boolean retry = true; // 스레드를 중지시킨다. thread.setRunning(false); while (retry) { try { thread.join(); // 메인 스레드와 합친다. retry = false; } catch (InterruptedException e) { } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

핵심적인 코드 public class MyThread extends Thread { … @Override public void run() { while (mRun) { Canvas c = null; try { c = mSurfaceHolder.lockCanvas(null); c.drawColor(Color.BLACK); // 캔버스의 배경을 지운다. synchronized (mSurfaceHolder) { for (Ball b : basket) { // basket의 모든 원소를 그린다. b.paint(c); } } finally { if (c != null) { mSurfaceHolder.unlockCanvasAndPost(c); }

서피스 뷰 예제