[.java로 View Control]

|
#자바 파일로 작성

StringEx extends Activity {
setContentView(new StringView(this));
StringView라는 클래스의 객체를 생성하여 StringEx를 넘겨준다.
그러면 StringView는 StringEx를 받아 거기에 그림을 그리거나 글을 쓴다.
StringView는 그림을 그리거나 글을 쓸 때 onDraw()가 필요하기 때문에 View를 상속받는다.
super.onDraw(canvas);를 가장 먼저 실행한 후, 원하는 작업 수행

1. onCreate
2. onStart
3. onResume
4. setContentView(new StringView(this));

StringEx.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package net.itisn.test;

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

public class StringEx extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(new StringView(this));
    }
}


StringView.java
package net.itisn.test;

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

public class StringView extends View {

	public StringView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		this.setBackgroundColor(Color.WHITE);
	}

	//그리기 함수
	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		
		//그리기 객체
		Paint paint = new Paint();
		paint.setAntiAlias(true);	//그리기 객체에 안티알리아스 적용

		//문자 크기 및 색상 설정
		paint.setTextSize(12);
		paint.setColor(Color.argb(255, 0, 0, 0));

		//폰 화면 가져와서 글자 쓰기
		canvas.drawText("화면 넓이" + this.getWidth() + 
				"화면 높이" + this.getHeight(),
				0, 30, paint);
		
		//문자열의 폭 구하기
		canvas.drawText("문자열 폭" + (int)paint.ascent(), 0, 60, paint);
		
		//문자 크기 16, 색상 빨간색 설정
		paint.setTextSize(16);
		paint.setColor(Color.argb(128, 255, 0, 0));
		
		//폰 화면(canvas)에 그리기
		canvas.drawText("두번째 문자", 0, 90, paint);
		
	}
}

'Android' 카테고리의 다른 글

[LifeCycle]  (0) 2010.08.17
[ShapeEx]  (0) 2010.08.16
[RelativeLayout] 0. 레이아웃 만들기  (0) 2010.08.13
XML 문법  (0) 2010.08.13
[CustomView] 4. Thread 이용하여 그림 움직이기  (0) 2010.08.12
And