java canvas Android,使用"canvas = Holder.lockCanvas();",Android Java时,canvas是空

我刚刚回到 android java,并且通过跟踪我在( 成功) 之前做的一个模板进行了一个快速游戏。 试图定义"画布"时,Holder.lockCanvas(); 返回"空"值( 我认为该命令本身可能失败) 。 通过执行以下操作,我已经检查曲面是否有效:if (!ourHolder.getSurface().isValid())

continue;

如果需要,它的余代码是 below,问题在底部,在类运行中。package creo.novus.tetris;

import java.util.Random;

import creo.novus.tetris.R;

import android.app.Activity;

import android.content.Context;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.graphics.Canvas;

import android.graphics.Color;

import android.graphics.Paint;

import android.os.Bundle;

import android.view.MotionEvent;

import android.view.SurfaceHolder;

import android.view.SurfaceView;

import android.view.View;

import android.view.View.OnTouchListener;

public class Main_game extends Activity implements OnTouchListener {

float touch_x, touch_y, screen_height, screen_width, game_height;

boolean once = true;

Bitmap left_pressed, left_unpressed, right_pressed, right_unpressed,

rotate_pressed, rotate_unpressed;

Canvas canvas;

Random generator = new Random();

GameView TetView;

int score;

float left_x;

float left_y;

float right_y;

float right_x;

float rotate_y;

float rotate_x;

@Override

protected void onCreate(Bundle savedInstanceState) {

//TODO Auto-generated method stub

super.onCreate(savedInstanceState);

TetView = new GameView(this);

TetView.setOnTouchListener(this);

left_unpressed = BitmapFactory.decodeResource(getResources(),

R.drawable.left_unpressed);

left_pressed = BitmapFactory.decodeResource(getResources(),

R.drawable.left_pressed);

right_unpressed = BitmapFactory.decodeResource(getResources(),

R.drawable.right_unpressed);

right_pressed = BitmapFactory.decodeResource(getResources(),

R.drawable.right_pressed);

rotate_unpressed = BitmapFactory.decodeResource(getResources(),

R.drawable.rotate_unpressed);

rotate_pressed = BitmapFactory.decodeResource(getResources(),

R.drawable.rotate_pressed);

setContentView(TetView);

}

@Override

protected void onResume() {

//TODO Auto-generated method stub

super.onResume();

TetView.resume();

}

@Override

protected void onPause() {

//TODO Auto-generated method stub

super.onPause();

TetView.pause();

}

@Override

public boolean onTouch(View v, MotionEvent event) {

//TODO Auto-generated method stub

touch_x = event.getX();

touch_y = event.getY();

return true;

}

public class GameView extends SurfaceView implements Runnable {

SurfaceHolder ourHolder;

Thread gameThread = null;

boolean isRunning = false;

Thread tetThread = null;

public GameView(Context context) {

super(context);

gameThread = new Thread(this);

tetThread = new Thread(this);

ourHolder = getHolder();

}

public void pause() {

isRunning = false;

while (true) {

try {

gameThread.join();

} catch (InterruptedException e) {

//TODO Auto-generated catch block

e.printStackTrace();

}

break;

}

gameThread = null;

tetThread = null;

}

public void resume() {

gameThread.start();

tetThread.start();

isRunning = true;

}

public void run() {

//TODO Auto-generated method stub

while (isRunning) {

if (!ourHolder.getSurface().isValid())

continue;

canvas = ourHolder.lockCanvas();

canvas.drawRGB(137, 137, 137);

if (once) {

//Initialization

Paint myPaint = new Paint();

myPaint.setColor(Color.BLACK);

myPaint.setStyle(Paint.Style.FILL);

myPaint.setTextSize(12);

screen_height = canvas.getHeight();

screen_width = canvas.getWidth();

game_height = (screen_height/6) * 5;

int button_height = (int) (screen_height - game_height);

rotate_x = (screen_width/4);

rotate_y = ((screen_height/6) * 5);

right_x = (screen_width/4) * 3;

right_y = rotate_y;

left_x = 0;

left_y = rotate_y;

Bitmap.createScaledBitmap(left_pressed,

(int) (screen_width/4), button_height, true);

Bitmap.createScaledBitmap(left_unpressed,

(int) (screen_width/4), button_height, true);

Bitmap.createScaledBitmap(right_pressed,

(int) (screen_width/4), button_height, true);

Bitmap.createScaledBitmap(right_unpressed,

(int) (screen_width/4), button_height, true);

Bitmap.createScaledBitmap(rotate_pressed,

(int) (screen_width/2), button_height, true);

Bitmap.createScaledBitmap(rotate_unpressed,

(int) (screen_width/2), button_height, true);

once = false;

}

if (touch_y> = rotate_y) {

if (touch_x

canvas.drawBitmap(left_pressed, left_x, left_y, null);

canvas.drawBitmap(rotate_unpressed, rotate_x, rotate_y, null);

canvas.drawBitmap(right_unpressed, right_x, right_y, null);

}else if(touch_x

canvas.drawBitmap(left_unpressed, left_x, left_y, null);

canvas.drawBitmap(rotate_pressed, rotate_x, rotate_y, null);

canvas.drawBitmap(right_unpressed, right_x, right_y, null);

}else{

canvas.drawBitmap(left_unpressed, left_x, left_y, null);

canvas.drawBitmap(rotate_unpressed, rotate_x, rotate_y, null);

canvas.drawBitmap(right_pressed, right_x, right_y, null);

}

}

}

}

}

}

任何帮助,都会感激你的,谢谢你的时间。

package person.tools.treasurebox.customview.widget import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Canvas import android.graphics.PorterDuff import android.util.AttributeSet import android.view.SurfaceHolder import android.view.SurfaceView import person.tools.treasurebox.R class AnimationSurfaceView(context: Context, attrs: AttributeSet) : SurfaceView(context, attrs) { companion object { const val BITMAP_STEP = 1 } private lateinit var bitmapBg: Bitmap private var flag: Boolean = false private var mSurfaceViewHeight: Int? = null private var mSurfaceViewWidth: Int? = null private var thread: Thread? = null private var mCanvas: Canvas? = null // 记录当前绘制的Bitmap的左上角x坐标 private var mBitPosX: Float = 0.0f private var state = State.LEFT init { holder.addCallback(object : SurfaceHolder.Callback { override fun surfaceCreated(holder: SurfaceHolder) { flag = true startAnimation() } override fun surfaceChanged( holder: SurfaceHolder, format: Int, width: Int, height: Int ) { // do nothing } override fun surfaceDestroyed(holder: SurfaceHolder) { flag = false } }) } // 动画 private fun startAnimation() { mSurfaceViewHeight = height mSurfaceViewWidth = width val mWidth = (mSurfaceViewWidth!! * 3) / 2 // 获取图片资源,转换位Bitmap,放大1.5倍 val bitmap = BitmapFactory.decodeResource(resources, R.drawable.telescope_test_img) bitmapBg = Bitmap.createScaledBitmap(bitmap, mWidth, mSurfaceViewHeight!!, true) // 开启画图子线程 thread = Thread { if (flag) { mCanvas = holder.lockCanvas() drawView() holder.unlockCanvasAndPost(mCanvas) try { Thread.sleep(50) } catch (e: InterruptedException) { e.printStackTrace() } } } thread?.start() } private fun drawView() { // 清屏幕 mCanvas?.drawColor(0, PorterDuff.Mode.CLEAR) // 绘制当前屏幕背景 mCanvas?.drawBitmap(bitmapBg, mBitPosX, 0f, null) when (state) { State.LEFT -> { mBitPosX -= BITMAP_STEP } else -> { mBitPosX += BITMAP_STEP } } if (mBitPosX <= -mSurfaceViewWidth!! / 2) { state = State.RIGHT } if (mBitPosX > 0) { state = State.LEFT } } enum class State { LEFT, RIGHT } } 为什么这个图没有动起来
09-14
package com.example.myapplication; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.os.Bundle; import android.view.SurfaceHolder; import android.view.SurfaceView; import androidx.appcompat.app.AppCompatActivity; import java.net.DatagramPacket; import java.net.DatagramSocket; public class VideoActivity extends AppCompatActivity { private static final int PORT = 8888; private static final int BUFFER_SIZE = 65535; private volatile boolean receiving = true; private SurfaceHolder surfaceHolder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SurfaceView surfaceView = findViewById(R.id.surface_view); surfaceHolder = surfaceView.getHolder(); surfaceHolder.addCallback(new SurfaceHolder.Callback() { @Override public void surfaceCreated(SurfaceHolder holder) { new Thread(new VideoReceiver()).start(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {} @Override public void surfaceDestroyed(SurfaceHolder holder) { receiving = false; } }); } private class VideoReceiver implements Runnable { @Override public void run() { try (DatagramSocket socket = new DatagramSocket(PORT)) { byte[] buffer = new byte[BUFFER_SIZE]; while (receiving) { DatagramPacket packet = new DatagramPacket(buffer, buffer.length); socket.receive(packet); // 将接收到的字节数据转换为位图 Bitmap bitmap = BitmapFactory.decodeByteArray( packet.getData(), 0, packet.getLength() ); // 在SurfaceView上绘制图像 if (bitmap != null) { Canvas canvas = surfaceHolder.lockCanvas(); if (canvas != null) { // 缩放到位图以适应SurfaceView尺寸 Bitmap scaledBitmap = Bitmap.createScaledBitmap( bitmap, canvas.getWidth(), canvas.getHeight(), true ); canvas.drawBitmap(scaledBitmap, 0, 0, null); surfaceHolder.unlockCanvasAndPost(canvas); scaledBitmap.recycle(); } bitmap.recycle(); } } } catch (Exception e) { e.printStackTrace(); } } } @Override protected void onDestroy() { super.onDestroy(); receiving = false; } } 根据上述相应的java文件写一个相应的activity_video.xml文件,并且上述程序要放在该xml界面内
09-23
package com.tencent.acgui; import android.app.*; import android.content.*; import android.content.res.*; import android.graphics.*; import android.os.*; import android.util.*; import android.view.*; public class FloatService extends Service { public static FloatService Instance; public static WindowManager manager = null; private MySurfaceView surfaceView = null; public static boolean mSurfaceViewIo = false; private DisplayMetrics dm = new DisplayMetrics(); private WindowManager.LayoutParams wmParams; public static void ShowFloat(Context context) { if (Instance == null) { Intent intent = new Intent(context, FloatService.class); context.startService(intent); } } @Override public void onCreate() { super.onCreate(); Instance = this; initData(); SetmSurfaceView(); } @Override public IBinder onBind(Intent intent) { return null; } private void initData() { if (manager == null) { manager = (WindowManager) Instance.getSystemService(WINDOW_SERVICE); } } private void SetmSurfaceView() { surfaceView = new MySurfaceView(Instance); surfaceView.setZOrderOnTop(true); manager.getDefaultDisplay().getRealMetrics(dm); surfaceView.getHolder().setFormat(PixelFormat.TRANSPARENT); wmParams = new WindowManager.LayoutParams(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { wmParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { wmParams.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES; } } else { wmParams.type = WindowManager.LayoutParams.TYPE_PHONE; } wmParams.format = PixelFormat.RGBA_8888; wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_FULLSCREEN; wmParams.gravity = Gravity.LEFT | Gravity.TOP; wmParams.x = 0; wmParams.y = 0; wmParams.width = dm.widthPixels; wmParams.height = dm.heightPixels; wmParams.alpha = 0.5f; if (manager != null) { mSurfaceViewIo = true; manager.addView(surfaceView, wmParams); } } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); manager.getDefaultDisplay().getRealMetrics(dm); if (wmParams != null && surfaceView != null) { wmParams.width = dm.widthPixels; wmParams.height = dm.heightPixels; manager.updateViewLayout(surfaceView, wmParams); } } } package com.tencent.acgui; import android.annotation.*; import android.content.*; import android.graphics.*; import android.os.*; import android.view.*; import android.view.inputmethod.*; public class TouchView extends View { private View mtouch; private InputMethodManager manager; private WindowManager.LayoutParams mtouchParams; public TouchView(Context context) { super(context); mtouch = this; manager = (InputMethodManager) mtouch.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); } private WindowManager.LayoutParams getAttributes(boolean isWindow) { WindowManager.LayoutParams params = new WindowManager.LayoutParams(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY; } else { params.type = WindowManager.LayoutParams.TYPE_PHONE; } params.flags = WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN; if (isWindow) { params.flags |= WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; } params.format = PixelFormat.RGBA_8888; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { params.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES; } params.gravity = Gravity.LEFT | Gravity.TOP; params.x = params.y = 0; params.width = params.height = isWindow ? WindowManager.LayoutParams.WRAP_CONTENT : WindowManager.LayoutParams.WRAP_CONTENT; return params; } public void initView() { mtouchParams = getAttributes(false); FloatService.manager.addView(mtouch, mtouchParams); updateTouchWinSize(); } @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouchEvent(MotionEvent event) { JNIInterface.MotionEventClick(event.getAction(), event.getRawX(), event.getRawY()); return false; } private void updateTouchWinSize() { final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { float[] rect = JNIInterface.GetImGuiwinsize(); mtouchParams.x = (int) rect[0]; mtouchParams.y = (int) rect[1]; mtouchParams.width = (int) rect[2]; mtouchParams.height = (int) rect[3]; FloatService.manager.updateViewLayout(mtouch, mtouchParams); handler.postDelayed(this, 20); } }, 20); } } package com.tencent.acgui; import android.annotation.*; import android.content.*; import android.graphics.*; import android.util.*; import android.view.*; public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback { private TouchView mtouch; private boolean jniLoaded = false; public MySurfaceView(Context context) { this(context, null); } private MySurfaceView(Context context, AttributeSet attrs) { this(context, attrs, 0); } private MySurfaceView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mtouch = new TouchView(context); this.setZOrderOnTop(true); this.getHolder().setFormat(PixelFormat.RGBA_8888); this.getHolder().addCallback(this); mtouch.initView(); } private void checkJNILoaded() { try { JNIInterface.verifySignature(getContext()); jniLoaded = true; } catch (UnsatisfiedLinkError e) { jniLoaded = false; try { System.loadLibrary("AcGui"); jniLoaded = true; } catch (Exception ex) { ex.printStackTrace(); } } } @Override public void surfaceCreated(@NonNull SurfaceHolder holder) { checkJNILoaded(); if (!jniLoaded) { JNIInterface.SurfaceCreate(holder.getSurface(), this.getWidth(), this.getHeight()); return; } try { byte[] fontData = JNIInterface.loadFontFromAssets(getContext(), "TextFont.ttf"); if (fontData != null && fontData.length > 0) { JNIInterface.setCustomFont(fontData, fontData.length); } } catch (UnsatisfiedLinkError e) { } catch (Exception e) { } JNIInterface.SurfaceCreate(holder.getSurface(), this.getWidth(), this.getHeight()); } @Override public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int Width, int Height) { if (jniLoaded) { JNIInterface.SurfaceChange(Width, Height); } } @Override public void surfaceDestroyed(@NonNull SurfaceHolder holder) { if (jniLoaded) { JNIInterface.SurfaceDestroyed(); } } @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouchEvent(MotionEvent event) { if (jniLoaded) { JNIInterface.MotionEventClick(event.getAction(), event.getRawX(), event.getRawY()); } return false; } }
最新发布
12-12
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值