[CustomView] 3. RobotView 그림 위치 지정 - 성공

|
#onSizeChanged()에서 그림 위치 셋팅 - 그림이 정상적으로 그려짐
[RobotView.java]
onSizeChanged()를 오버라이드하여 그 안에 작성한다.
package net.itisn.test;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;

public class RobotView extends View {

    private Drawable image;
    private int viewWidth, viewHeight;
    private int imageWidth, imageHeight;
    private int x, y;

    public RobotView(Context context, AttributeSet attrs) {
    	super(context, attrs);
    	// TODO Auto-generated constructor stub
    	image = this.getResources().getDrawable(R.drawable.su);
    }

    @Override
    protected void onDraw(Canvas canvas) {
    	// TODO Auto-generated method stub
    	image.draw(canvas);
    	super.onDraw(canvas);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    	// TODO Auto-generated method stub
    	viewWidth = this.getWidth();
    	viewHeight = this.getHeight();

    	imageWidth = image.getIntrinsicWidth();
    	imageHeight = image.getIntrinsicHeight();

    	x = viewWidth / 2 - imageWidth / 2;
    	y = viewHeight / 2 - imageHeight / 2;
    	image.setBounds(x, y, x + imageWidth, y + imageHeight);

    	super.onSizeChanged(w, h, oldw, oldh);
    }
}

[main.xml]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />

<net.itisn.test.RobotView
    android:id="@+id/su"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    />

</LinearLayout>

'Android' 카테고리의 다른 글

[RelativeLayout] 0. 레이아웃 만들기  (0) 2010.08.13
XML 문법  (0) 2010.08.13
[CustomView] 4. Thread 이용하여 그림 움직이기  (0) 2010.08.12
[CustomView] 1. 그림 정가운데 출력  (0) 2010.08.12
[CustomView] 0. RobotView 생성  (0) 2010.08.11
And