본문 바로가기

안드로이드 Android

[모바일프로그래밍] 7-5 서피스 뷰

ccSurfaceView: 안드로이드에서 게임처럼 화면이 자주 바뀌는 경우에 사용하는 위젯

MainActivity.java

package com.example.myapplication;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

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

MySurfaceView.java

package com.example.myapplication;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback {
    Context mContext;
    SurfaceHolder mHolder;
    RenderingThread mRThread;

    public MySurfaceView(Context context) {
        super(context);
        mContext = context;
        mHolder = getHolder();
        mHolder.addCallback(this);
        mRThread = new MySurfaceView.RenderingThread();
    }
    
    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        // Surface가 만들어질 때 호출됨
         mRThread.start();
    }
    
    @Override
        public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) {
        // Surface가 변경될 때 호출됨
    }
    
    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        // Surface가 종료될 때 호출됨
         try {
             mRThread.join();
         } catch (InterruptedException e) {
             e.printStackTrace();
         }
    }

     class RenderingThread extends Thread {
        Bitmap img_android;
        public RenderingThread() {
            Log.d("RenderingThread", "RenderingThread()");
            img_android = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.android);
        }
    
        public void run() {
            float angle = 0;
            Log.d("RenderingThread", "run()");
    //            Canvas canvas = null;
            while (true) {
                Canvas canvas = null;
                canvas = mHolder.lockCanvas();
                angle += 1;
                try {
                    synchronized (mHolder) {
                        canvas.rotate(angle);
                        canvas.translate(500, 500);
                        canvas.drawBitmap(img_android, 0, 0, null);
                    }
                } finally {
                    if (canvas == null) return;
                    mHolder.unlockCanvasAndPost(canvas);
                }
            }
        }
     }
}