您好,登錄后才能下訂單哦!
//MysurfaceView.java
package com.example.surfaceview;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
public class MysurfaceView extends SurfaceView implements Callback{
private SurfaceHolder sfh;
private Paint paint;
private int textX=10,textY=10;
public MysurfaceView(Context context)
{
super(context);
sfh=this.getHolder();//控制SurfaceView的大小 格式 主要用于監聽SurfaceView的狀態
//其實surfaceView只是保存當前視圖的像素數據 在使用surfaceView時 并不會與surfaceview直接打交道
//而是通過surfaceHolder來控制 使用surfaceHolder的lockCanvas()函數獲取到surfaceView的
//canvas對象 。在通過在canvas上繪制內容來修改surfaceView中的數據
//locakCanvas不僅獲取canvas 還對獲取的canvas進行加鎖
sfh.addCallback(this);//將其監聽接口實例傳入..完成對surfaceView的監聽
paint=new Paint();
paint.setColor(Color.WHITE);
setFocusable(true);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
myDraw();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
public void myDraw()
{
Canvas canvas=sfh.lockCanvas();
canvas.drawRect(0, 0,this.getWidth(),this.getHeight(),paint);//the first method 繪制一個和手機屏幕一樣大小的矩形
canvas.drawColor(Color.BLACK);//the second methos繪制顏色填充整個屏幕
canvas.drawRGB(0,0,0);//the third method 繪制顏色填充整個屏幕
canvas.drawText("game", textX, textY, paint);
sfh.unlockCanvasAndPost(canvas);
}
public boolean onTouchEvent(MotionEvent event)
{
textX=(int)event.getX();
textY=(int)event.getY();
myDraw();
invalidate();
return true;
}
}
//MainActivity.java如下:
package com.example.surfaceview;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MysurfaceView(this));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。