gpt4 book ai didi

java - SurfaceView 在其上绘制时变黑

转载 作者:太空狗 更新时间:2023-10-29 14:50:58 26 4
gpt4 key购买 nike

我有一个捕捉触摸事件的表面 View ,然后在 Canvas 上绘制一个点。但是当我触摸时,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;
}
}

游戏经典.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 的颜色时,它起作用了。然而,绘制点仍然会将表面 View 变成黑色。

最佳答案

当您覆盖 onTouch() 时,您需要调用 super.onTouch()。可能是问题所在。

关于java - SurfaceView 在其上绘制时变黑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35381944/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com