我有一个抓住touchEvents的surfaceview,然后在画布上绘制一个点。但是当我触摸时,SurfaceView会从红色变为黑色,而不是绘制一个点。请看一下我的代码:
GamemodeClassic.java
public class GamemodeClassic extends AppCompatActivity implements Runnable, View.OnTouchListener {
private SurfaceView view;
private GameClassic game;
@Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_gamemode_classic);
init();
}
public void init() {
view = (SurfaceView) findViewById(R.id.classic_view);
game = new GameClassic(this);
view.getHolder().addCallback(game);
view.setOnTouchListener(game);
}
@Override
public void run() {
}
@Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
}
GameClassic.java
public class GameClassic extends SurfaceView implements SurfaceHolder.Callback, View.OnTouchListener {
SurfaceHolder mainHolder;
public GameClassic(Context context) {
super(context);
setFocusable(true);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
mainHolder = holder;
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
initDraw(holder);
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
public void initDraw(SurfaceHolder holder) {
Canvas canvas = mainHolder.lockCanvas();
if(canvas == null) {
Log.v("testlog", "GameClassic.java - Canvas not available");
}else{
Log.v("testlog", "GameClassic.java - Canvas found, drawing");
canvas.drawRGB(255, 0, 0);
}
holder.unlockCanvasAndPost(canvas);
}
public void drawPoint(float x, float y) {
Canvas canvas = mainHolder.lockCanvas();
if(canvas != null) {
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.BLUE);
canvas.drawPoint(x, y, paint);
mainHolder.unlockCanvasAndPost(canvas);
}else{
Log.v("testlog", canvas + "");
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.v("testlog", event.getAction() + "sfsfsf");
if(event.getAction() == MotionEvent.ACTION_DOWN) {
drawPoint(event.getX(), event.getY());
Log.v("testlog", "drawing point on (" + event.getX() + ";" + event.getY() + ")");
}
return true;
}
}
提前致谢
修改
事实证明,我必须将行holder.unlockCanvasAndPost(canvas)
更改为mainHolder.unlockCanvasAndPost(canvas)
。仍然没有任何改进,但是当我尝试使用drawPoint中的canvas.drawRGB()更改surfaceview的颜色时,它可以正常工作。然而,绘制点仍然会将表面视图变为黑色。
答案 0 :(得分:0)
当您覆盖onTouch()
时,您需要拨打super.onTouch()
。可能是问题。
答案 1 :(得分:0)
显然,当您锁定画布并在其上绘制时,整个画布将重置为其默认颜色,即黑色。当你在顶部画一个点时,蓝色几乎看不到,这让我觉得整个屏幕都变黑了。在该点之前重新绘制背景是解决方案。
答案 2 :(得分:0)
在您的GameClassic构造函数中,将alpha设置为零。像这样:
public GameClassic (Context context) {
super (context);
setFocusable(true);
setAlpha(0); // this is the secret
}