2012年5月24日 星期四

[ANDROID]SurfaceHolder.Callback方法練習


SurfaceView_test2Activity.java

package bear.Graphis.surfaceView_test2;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class SurfaceView_test2Activity extends Activity {



    class MysurfaceView extends SurfaceView implements SurfaceHolder.Callback{

     public MysurfaceView(Context context) {
      super(context);
      // TODO Auto-generated constructor stub
      getHolder().addCallback(this);
     }
 
   

     public void surfaceCreated(SurfaceHolder holder) {//當Surface第一次創建後會立即執行該函數,盡量別在這邊畫
     
      Canvas canvas =holder.lockCanvas();//加鎖
      Resources res=getResources();//取得資源檔
      BitmapDrawable bmpDrwable = (BitmapDrawable) res.getDrawable(R.drawable.icon);//構造一個BitmapDrawable
      Bitmap bmp = bmpDrwable.getBitmap();//取得BitmapDrawable內的圖片
      Paint mypaint =new Paint();
      //設定Paint屬性
      mypaint.setColor(Color.GREEN);
      mypaint.setTextSize(40);
     
      //設定Canvas屬性
      canvas.drawColor(Color.WHITE);
      canvas.drawText("SurfaceView.Callback", 0, 40, mypaint);//顯示字
      canvas.drawBitmap(bmp, 0, 100, mypaint);//顯示圖片
      holder.unlockCanvasAndPost(canvas);//解鎖
     }



     public void surfaceChanged(SurfaceHolder holder, int format, int width,
       int height) {
      //當Surface的狀態(大小和格式)發生變化的時候會調用該函数
     
     }

     public void surfaceDestroyed(SurfaceHolder holder) {
      // Surface被摧毁前會调用该函数,該函数被调用後就不能繼续使用Surface了,一般在該函数中來清理使用的資源
     
     }
   
     }


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MysurfaceView(this));//將創建的MysurfaceView設定成顯示畫面
   
    }

} 



main.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" >

</LinearLayout>




結果:




沒有留言:

張貼留言