Android全屏WindowManager覆盖View可点击,窗口上View也可点击 10C

全屏的WindowManager ,会把ontouch 拦截掉,或者就是获取不到ontouch,怎么可以实现
窗口获取ontouch 下面的view也可以获取ontouch

3个回答

你可以参考下我的列子
全屏应用上浮一层未全屏的view(view上有button控件),
若是没有点击到view上的button控件,事件分发到下一层全屏应用上,
若是点击了button,则进行事件消费,不会分发到下一层全屏上。
对view进行ontouch监听
图片说明
更改view的LayoutParams flag
图片说明

qq_28210079
张禹754178 调用的时候不能实时改变啊
接近 2 年之前 回复
qq_28210079
张禹754178 这个方法是不是在ontouch
接近 2 年之前 回复
qq_28210079
张禹754178 ok 我试一下
接近 2 年之前 回复

全屏应用上浮一层未全屏的view(view上有button控件),
若是没有点击到view上的button控件,事件分发到下一层全屏应用上,
若是点击了button,则进行事件消费,不会分发到下一层全屏上。
对view进行ontouch监听
图片说明
更改view的LayoutParams flag
图片说明

重写view ontouch事件里面返回false

baidu_30233079
baidu_30233079 不过我觉得还是有机会的,你试试把这三个接口都重写dispatchTouchEvent(事件的分发),onInterceptTouchEvent(事件的拦截),onTouchEvent(事件的处理)。
接近 2 年之前 回复
qq_28210079
张禹754178 悬浮窗,两个view是可以,windowmanager,是不在一个层级
接近 2 年之前 回复
baidu_30233079
baidu_30233079 你说的windowmanager真没用过,两个view的可以。为啥用windowmanager?
接近 2 年之前 回复
baidu_30233079
baidu_30233079 可以的,我以前就这样实现过,如果只重写ontouch不行,你可以把dispatch接口也重写。一定可以的
接近 2 年之前 回复
qq_28210079
张禹754178 是windowmanager 重新view没有用 穿透不到下面
接近 2 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
android webview加载服务器上js自动轮播图片不显示问题,求大神帮忙
这个是手机版网站地址:m.daxuepai.com.cn 正常打开首页应该有轮播图片,如下图: ![图片说明](https://img-ask.csdn.net/upload/201601/20/1453302838_761230.png) 轮播功能是做web前端的人用js写的。 以下是我android中的代码,主要就是用webview加载了相应地址的资源,但是我加载了后那个轮播图就没有显示,代码如下: package com.example.testwebkit; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.Window; import android.view.WindowManager; import android.webkit.WebChromeClient; import android.webkit.WebSettings.ZoomDensity; import android.webkit.WebView; import android.webkit.WebViewClient; public class MainActivity extends Activity { private WebView webView; @SuppressWarnings("deprecation") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); int flag=WindowManager.LayoutParams.FLAG_FULLSCREEN; //获得当前窗体对象 Window window=MainActivity.this.getWindow(); //设置当前窗体为全屏显示 window.setFlags(flag, flag); setContentView(R.layout.activity_main); webView = (WebView) findViewById(R.id.webView1); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setDomStorageEnabled(true); webView.loadUrl("http://m.daxuepai.com.cn"); webView.setWebChromeClient(new WebChromeClient(){ @Override public void onReceivedTitle(WebView view, String title) { // TODO Auto-generated method stub super.onReceivedTitle(view, title); } }); webView.setWebViewClient(new WebViewClient(){ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // TODO Auto-generated method stub view.loadUrl(url); return super.shouldOverrideUrlLoading(view, url); } }); } } 打开后效果如下: ![图片说明](https://img-ask.csdn.net/upload/201601/20/1453303268_724677.png) 我用的是MX3,手机自带浏览器、手机版猎豹浏览器同样不加载轮播图片,手机qq浏览器、微信关注公众号后进首页都可以加载那个轮播图片,有大神能告诉我是为什么么? ``` ```
webview 视频全屏播放问题
当全屏播放时候点击视频会点击到webview,即使webview设置成gone还是会触发, 所以无法弹出进度条,只有当activity设置有标题栏才不会出现这个问题,一旦设置成无标题栏就出问题了,为什么 下面是webview代码 webview.setWebChromeClient(new WebChromeClient() { @Override public void onShowCustomView(View view, CustomViewCallback callback) { // TODO Auto-generated method stub setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); layout.addView(view); webview.setVisibility(View.GONE); super.onShowCustomView(view, callback); }
在Android studio运行模拟器时报错Emulator: qemu_ram_alloc_user_backed: call
每次启动模拟器都会报这个错误,刚接触Android开发不知道为啥,有没有大佬解答一下。 ``` package com.example.lenovo.myapplication; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.Display; import android.view.View; import android.view.WindowManager; public class MainActivity extends AppCompatActivity { private int zmkuan; int zmGao; //小球的变量 float qiu_size = 16; float qiu_sudu =3; float qiu_shang = 90; float qiuX; float qiuY; //柱子的变量 float zhu_gao ; float zhu_gao_2; float zhu_kaun = 80; float zhu_kaun_2 = 80; float zhuX; float zhuY; float zhuX_2; float zhuY_2; float zhu_sudu; int num = 0;//小球通过柱子数 boolean jieshu = false;//盘孤单小球是否结束 MyGameView myGameView;//为了能在全局访问到这个变量 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //设置为全屏,固定写法 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); //使游戏横屏,修改配置文件AndroidMainifest.xml: <activity android:name=".MainActivity" android:screenOrientation="landscape"> //获取游戏视图 MyGameView myGameView = new MyGameView(this); setContentView(myGameView); //获取窗口的一个管理器,固定写法 WindowManager windowManager = getWindowManager(); Display display = windowManager.getDefaultDisplay(); DisplayMetrics metrics = new DisplayMetrics(); display.getMetrics(metrics); //获取屏幕的宽和高 zmkuan = metrics.widthPixels; zmGao = metrics.heightPixels; play(); } public void play(){ jieshu = false; //设置两根柱子的初始位置 zhuX = zmkuan - zhu_kaun; zhuY = 0; zhuX_2 = zmkuan - zhu_kaun_2; zhuY_2 = zmGao; zhu_gao = zmGao/2 - 200; zhu_gao_2 = zmGao -zhu_gao -200; num = 0; zhu_sudu = 5; qiu_sudu = 3.5f; qiu_shang = 90; qiuX = 50; qiuY = zmGao/2; handler.sendEmptyMessage(0x123); } Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == 0x123){ myGameView.invalidate(); } } }; class MyGameView extends View { Paint paint = new Paint(); public MyGameView(Context context) { super(context); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); paint.setStyle(Paint.Style.FILL); paint.setAntiAlias(true);//设置抗锯齿 if (jieshu){ //执行游戏结束后的效果 }else { paint.setColor(Color.RED); paint.setTextSize(80); canvas.drawText(num+"",zmkuan/2-10,80,paint); canvas.drawCircle(qiuX, qiuY, qiu_size, paint); //绘制上柱子 paint.setColor(Color.rgb(80,80,200)); canvas.drawRect(zhuX,zhuY,zhuX+zhu_kaun,zhuY+zhu_gao,paint); //绘制下柱子 canvas.drawRect(zhuX_2,zhuY_2,zhuX_2+zhu_kaun_2,zhuY_2+zhu_gao_2,paint); } } } } ``` event log报错信息:![图片说明](https://img-ask.csdn.net/upload/201904/16/1555399509_788338.png)
点击textview,调用showDialog方法弹出对话框,再点击textview,对话框消失,怎么实现啊?
//showDialog()方法 private void showDailog() { //R.style.***一定要写,不然不能充满整个屏宽,引用R.style.AppTheme就可以 View view = View.inflate(this, R.layout.dialog, null); Window window = dialog.getWindow(); window.setGravity(Gravity.BOTTOM); //设置dialog弹出时的动画效果,从屏幕底部向上弹出 dialog.setCanceledOnTouchOutside(true); dialog.show(); window.setContentView(view); WindowManager.LayoutParams params = window.getAttributes(); //设置窗口宽度为充满全屏 params.width = WindowManager.LayoutParams.MATCH_PARENT;//如果不设置,可能部分机型出现左右有空隙,也就是产生margin的感觉 //设置窗口高度为包裹内容 params.height = WindowManager.LayoutParams.WRAP_CONTENT; params.flags = WindowManager.LayoutParams.DIM_AMOUNT_CHANGED;//就是这个属性导致window后所有的东西都成暗淡 params.dimAmount = 1.0f;//设置对话框的透明程度背景 //将设置好的属性set回去 window.setAttributes(params); }
做个打小飞机游戏的bug,关于图片移动的问题,有时候移动图片移动多次会卡死,不动了,如何解决?
public class PlaneView extends View { public float currentX; public float currentY; private final Bitmap mBitmap_plane; public PlaneView(Context context) { super(context); //将图片转换成Bitmap形式 mBitmap_plane = BitmapFactory.decodeResource(context.getResources(), R.drawable.plane); //设置焦点 setFocusable(true); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //创建画笔 Paint p = new Paint(); //在画布上画一张图片 canvas.drawBitmap(mBitmap_plane,currentX,currentY,p); } } import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.DisplayMetrics; import android.view.Display; import android.view.KeyEvent; import android.view.View; import android.view.WindowManager; import android.widget.ImageView; public class MainActivity extends AppCompatActivity { private int speed = 10; private PlaneView mPv; private myOnKeyListener listener = null; private ImageView mImageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getSupportActionBar().hide(); //全屏显示 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); mPv = new PlaneView(this); setContentView(mPv); mPv.setBackgroundResource(R.color.colorPrimary); //获取窗口管理器 WindowManager windowManager = getWindowManager(); Display defaultDisplay = windowManager.getDefaultDisplay(); DisplayMetrics metrics = new DisplayMetrics(); //获取屏幕的宽高 defaultDisplay.getMetrics(metrics); //设置飞机的初始位置 mPv.currentX = metrics.widthPixels / 2; mPv.currentY = metrics.heightPixels - 40; mPv.setOnKeyListener(listener == null ? new myOnKeyListener() : listener); } class myOnKeyListener implements View.OnKeyListener { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { switch (event.getKeyCode()) { case KeyEvent.KEYCODE_S: mPv.currentY += speed; break; case KeyEvent.KEYCODE_W: mPv.currentY -= speed; break; case KeyEvent.KEYCODE_A: mPv.currentX -= speed; break; case KeyEvent.KEYCODE_D: mPv.currentX += speed; break; } mPv.invalidate(); return true; } } } 当移动多次就卡死不动了,LogCat也没有打印日志,我的开发环境是AS2.1
Android直接跳转activity报错
每次运行总是报错,能进入软件,但跳转时报错 ``` package com.text.Mark1; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.Window; import android.view.WindowManager; public class welcome extends Activity{ @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//全屏显示 setContentView(R.layout.welcome2); new Handler().postDelayed(new Runnable(){ @Override public void run(){ Intent intent = new Intent (welcome.this,login.class); startActivity(intent); welcome.this.finish(); } }, 1000); } } ``` 12-26 09:09:33.025: E/AndroidRuntime(555): FATAL EXCEPTION: main 12-26 09:09:33.025: E/AndroidRuntime(555): android.content.ActivityNotFoundException: Unable to find explicit activity class {com.text.Mark1/com.text.Mark1.login}; have you declared this activity in your AndroidManifest.xml? 12-26 09:09:33.025: E/AndroidRuntime(555): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1508) 12-26 09:09:33.025: E/AndroidRuntime(555): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1384) 12-26 09:09:33.025: E/AndroidRuntime(555): at android.app.Activity.startActivityForResult(Activity.java:3190) 12-26 09:09:33.025: E/AndroidRuntime(555): at android.app.Activity.startActivity(Activity.java:3297) 12-26 09:09:33.025: E/AndroidRuntime(555): at com.text.Mark1.welcome$1.run(welcome.java:25) 12-26 09:09:33.025: E/AndroidRuntime(555): at android.os.Handler.handleCallback(Handler.java:605) 12-26 09:09:33.025: E/AndroidRuntime(555): at android.os.Handler.dispatchMessage(Handler.java:92) 12-26 09:09:33.025: E/AndroidRuntime(555): at android.os.Looper.loop(Looper.java:137) 12-26 09:09:33.025: E/AndroidRuntime(555): at android.app.ActivityThread.main(ActivityThread.java:4340) 12-26 09:09:33.025: E/AndroidRuntime(555): at java.lang.reflect.Method.invokeNative(Native Method) 12-26 09:09:33.025: E/AndroidRuntime(555): at java.lang.reflect.Method.invoke(Method.java:511) 12-26 09:09:33.025: E/AndroidRuntime(555): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 12-26 09:09:33.025: E/AndroidRuntime(555): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 12-26 09:09:33.025: E/AndroidRuntime(555): at dalvik.system.NativeStart.main(Native Method)
android这段代码为什么无限启动相机?应该怎么改?
package nzy.ssp; import java.io.File; import nzy.ssp.net.AuthSina.common.InfoHelper; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.util.Log; import android.view.Window; import android.view.WindowManager; import android.widget.Toast; //定义一个类,使其实现拍照并保存功能 public class ActivityTakePic extends Activity { // 定义类的成员变量 private int TAKE_PICTURE = 1; private String TAG = "ActivityTakePic"; public static String thisLarge = null; private String theSmall = null; public static Uri photoUri; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //设置全屏 requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); //setContentView(R.layout.main); Toast.makeText(this, "启动拍照功能……", Toast.LENGTH_SHORT).show(); // 手机拍照 opentakePicDialog(); } private boolean checkSdCard() { if (android.os.Environment.getExternalStorageDirectory().equals( android.os.Environment.MEDIA_MOUNTED)) { return true; } else { return false; } } // 拍照 private void opentakePicDialog() { if (!checkSdCard()) { Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); startActivityForResult(intent, TAKE_PICTURE); } else { Toast.makeText(ActivityTakePic.this, "你手机上不存在存储卡", Toast.LENGTH_LONG).show(); } } /* * 相机拍照回调函数 * * @see android.app.Activity#onActivityResult(int, int, * android.content.Intent) */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == TAKE_PICTURE) { if (resultCode == RESULT_OK) { // super.onActivityResult(requestCode, resultCode, data); Log.i(TAG, TAG); Intent intent = new Intent(); String camerName = InfoHelper.getFileName(); Log.i(TAG, "camerName = " + camerName); String fileName = "Share" + camerName + ".jpg"; File camerFile = new File(InfoHelper.getCamerPath(), fileName); theSmall = InfoHelper.getCamerPath() + fileName; thisLarge = getLatestImage(); Log.i(TAG, "theSmall = " + theSmall); Log.i(TAG, "thisLarge = " + thisLarge); photoUri = Uri.fromFile(camerFile); data.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, photoUri); intent.putExtras(data); intent.putExtra("int", 0); intent.setClass(ActivityTakePic.this, ActivityMain.class); startActivity(intent); } } } /** * 获取SD卡中最新图片路径 * * @return */ @SuppressWarnings("unused") protected String getLatestImage() { String latestImage = null; String[] items = { MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA }; Cursor cursor = managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, items, null, null, MediaStore.Images.Media._ID + " desc"); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { latestImage = cursor.getString(1); break; } } return latestImage; } }
android 自定义camera 自动拍照
可以自动拍照的是魅族android版本5.01,不能自动拍照的是android版本5.1。是系统问题吗? 自动拍照功能在一些手机上可以使用,一些不能用。求原因 。坐等答案。 ``` public class CameraActivity extends Activity { private CameraView view; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().clearFlags( WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN); requestWindowFeature(Window.FEATURE_NO_TITLE);// 设置横屏模式以及全屏模式 view = new CameraView(this);// 通过一个surfaceview的view来实现拍照 view.setId(1); view = new CameraView(this, this); setContentView(R.layout.camera_layout); RelativeLayout relative = (RelativeLayout) this.findViewById(R.id.ly); RelativeLayout.LayoutParams Layout = new RelativeLayout.LayoutParams(3, 3);// 设置surfaceview使其满足需求无法观看预览 Layout.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 1); Layout.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 1); relative.addView(view, Layout); } } (2) CameraView.java package com.camera.test; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Point; import android.graphics.PointF; import android.hardware.Camera; import android.hardware.Camera.AutoFocusCallback; import android.hardware.Camera.ShutterCallback; import android.media.AudioManager; import android.media.FaceDetector; import android.media.FaceDetector.Face; import android.os.Environment; import android.os.Handler; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.widget.Toast; public class CameraView extends SurfaceView implements SurfaceHolder.Callback, Camera.PictureCallback { private SurfaceHolder holder; private Camera camera; private Camera.Parameters parameters; private Activity act; private Handler handler = new Handler(); private Context context; private SurfaceView surfaceView; private AudioManager audio; private int current; public CameraView(Context context) { super(context); surfaceView = this; audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); final int current = audio.getRingerMode(); audio.setRingerMode(AudioManager.RINGER_MODE_SILENT); this.context = context; holder = getHolder();// 生成Surface Holder holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);// 指定Push Buffer handler.postDelayed(new Runnable() { @Override public void run() { if (camera == null) { handler.postDelayed(this, 1 * 1000);// 由于启动camera需要时间,在此让其等两秒再进行聚焦知道camera不为空 } else { camera.autoFocus(new AutoFocusCallback() { @Override public void onAutoFocus(boolean success, Camera camera) { if (success) { camera.takePicture(new ShutterCallback() {// 如果聚焦成功则进行拍照 @Override public void onShutter() { } }, null, CameraView.this); } else { } } }); } } }, 2 * 1000); } public CameraView(Context context, Activity act) {// 在此定义一个构造方法用于拍照过后把CameraActivity给finish掉 this(context); this.act = act; } @Override public void surfaceCreated(final SurfaceHolder holder) { // TODO Auto-generated method stub camera = Camera.open();// 摄像头的初始化 handler.postDelayed(new Runnable() { @Override public void run() { if (holder != null) { try { camera.setPreviewDisplay(holder); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { handler.postDelayed(this, 1 * 1000); } } }, 2 * 1000); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // TODO Auto-generated method stub parameters = camera.getParameters(); camera.setParameters(parameters);// 设置参数 camera.startPreview();// 开始预览 } @Override public void surfaceDestroyed(SurfaceHolder holder) { // TODO Auto-generated method stub } public void onPictureTaken(byte[] data, Camera camera) {// 拍摄完成后保存照片 try { Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); String time = format.format(date); //在SD卡上创建文件夹 File file = new File(Environment.getExternalStorageDirectory() + "/myCamera/pic"); if (!file.exists()) { file.mkdirs(); } String path = Environment.getExternalStorageDirectory() + "/myCamera/pic/" + time + ".jpg"; data2file(data, path); camera.setPreviewCallback(null); camera.stopPreview(); camera.release(); camera = null; holder.removeCallback(CameraView.this); audio.setRingerMode(current); act.finish(); //uploadFile(path); } catch (Exception e) { } } private void data2file(byte[] w, String fileName) throws Exception {// 将二进制数据转换为文件的函数 FileOutputStream out = null; try { out = new FileOutputStream(fileName); out.write(w); out.close(); } catch (Exception e) { if (out != null) out.close(); throw e; } } // private void uploadFile(String filePath)// 拍照过后上传文件到服务器 // { // } } ```
Android 怎么将主程序添加到欢迎界面里面
我做好了一个欢迎界面,并且做了下按钮触发,里面什么都还没有,我这边有一个游戏主程序,应该怎么样才能合理的添加进去呢? 添加的结果就是 点击这个按钮 就进入这个主程序。下面是代码 这个是我的欢迎界面的代码 package sen.tan; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; public class dazhuankuaiActivity extends Activity { BallView myview; public static int screenWidth ; public static int screenHeight; private TextView textview; Button kaishi,jieshu,guanyu; ImageView image; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); String string = "欢迎进入疯狂打砖块游戏"; image = (ImageView) this.findViewById(R.id.image); image.setImageResource(R.drawable.img1); textview =(TextView) this.findViewById(R.id.textview); textview.setTextSize(20); textview.setTextColor(Color.GREEN); textview.setBackgroundColor(Color.RED); textview.setText(string); kaishi=(Button)findViewById(R.id.button1); guanyu=(Button)findViewById(R.id.button2); jieshu=(Button)findViewById(R.id.button3); kaishi.setWidth(250); guanyu.setWidth(200); jieshu.setWidth(150); kaishi.setTextSize(35); guanyu.setTextSize(29); jieshu.setTextSize(24); jieshu.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v) { dazhuankuaiActivity.this.finish(); } }); guanyu.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v){ textview.setText("本游戏由xxx制作,此游戏控制左右按键,来回移动挡板,不让小球掉落,当小球把上方砖块全部打完时,游戏胜利"); } }); kaishi.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v) { } }); 下面是我找到的主程序 package ab.cc; import android.app.Activity; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.Window; import android.view.WindowManager; public class BaomingActivity extends Activity { BallView myView; static int screenWidth; static int screenHeight; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* 定义DisplayMetrics对象 */ DisplayMetrics dm = new DisplayMetrics(); /* 取得窗口属性 */ getWindowManager().getDefaultDisplay().getMetrics(dm); /* 窗口的宽度 */ screenWidth = dm.widthPixels; /* 窗口的高度 */ screenHeight = dm.heightPixels; // setTitle("宽"+screenWidth+" 高"+screenHeight); /* 设置为无标题栏 */ requestWindowFeature(Window.FEATURE_NO_TITLE); /* 设置为全屏模式 */ getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); myView = new BallView(this); //设置显示GameSurfaceView视图 setContentView(myView); }//end of onCreate() //触笔事件 public boolean onTouchEvent(MotionEvent event) { return true; } //按键按下事件 public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { //菜单按键-设为初始菜单 case KeyEvent.KEYCODE_MENU: myView.resetGame(); //重新开始 break; //中间按键 case KeyEvent.KEYCODE_DPAD_CENTER: myView.ball_isRun = !myView.ball_isRun;//开始//暂停 break; //左方向键 case KeyEvent.KEYCODE_DPAD_LEFT: if(myView.ball_isRun){ if(myView.board_left<=myView.board_x_move) { myView.board_left=0; myView.board_right=myView.board_length; }else{ myView.board_left-=myView.board_x_move; myView.board_right-=myView.board_x_move;} } break; //右方向键 case KeyEvent.KEYCODE_DPAD_RIGHT: if(myView.ball_isRun){ if(screenWidth-myView.board_right<=myView.board_x_move ) { myView.board_left=screenWidth-myView.board_length; myView.board_right=screenWidth; }else{ myView.board_left+=myView.board_x_move; myView.board_right+=myView.board_x_move; } } break; //上方向键 case KeyEvent.KEYCODE_DPAD_UP: if(myView.ball_isRun){ if( myView.board_alterable_top==myView.board_default_top) { myView.board_alterable_top-=myView.boardYadd; myView.board_alterable_bottom-=myView.boardYadd; } } break; //下方向键 case KeyEvent.KEYCODE_DPAD_DOWN: if(myView.ball_isRun){ if( myView.board_alterable_top==myView.board_default_top-myView.boardYadd ) { myView.board_alterable_top=myView.board_default_top; myView.board_alterable_bottom=myView.board_alterable_top+myView.board_thickness; } } break; //返回键 case KeyEvent.KEYCODE_BACK: this.finish(); break; }//end switch return false; } //按键弹起事件 public boolean onKeyUp(int keyCode, KeyEvent event) { return true; } public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { return true; } } package ab.cc; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RadialGradient; import android.graphics.Shader; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; public class BallView extends SurfaceView implements SurfaceHolder.Callback, Runnable { //线程延时控制 final int ball_sleep=1;//毫秒,延时越大,球速越慢 final int ball_r= 8;//小球半径 final float ball2_r= 8;//底下滚珠小球半径 final int ballXorYadd = 4;//小球的基本位移。测试可行值:2,4 //获取屏幕宽度和高度 int screen_width;//320; int screen_height;//480; //砖的属性 int brick_width;//每块砖宽 int brick_height;//每块砖高 boolean brick_exist[];//砖是否存在 int k ;// 列//到for循环里才初始化 int j ;// 行 int brick_left = brick_width*(k-1);//到判断语句才初始化 int brick_right = brick_width*k; int brick_top = brick_height*j; int brick_bottom = brick_height*(j+1); //挡板的属性 int board_length;//挡板长度:80比较合适,可以随意修改,但别超过screen_width final int boardYadd = 16;//按上下键时挡板y方向位移量。经验证4、8、16可以,12不行 final int board_x_move = 30;//挡板x方向位移量:可以随意自定义 int board_left;//挡板左侧(可变) int board_right;//挡板右侧(可变) int board_thickness;//挡板厚度 int board_default_top;//即435,挡板的top面初始位置 int board_alterable_top;//挡板上侧(可变) int board_alterable_bottom;//挡板下侧(可变) int ball_default_x;//球的初始x坐标 int ball_default_y;//球的初始y坐标 //球的即时坐标(可变): int ball_x;//球心横坐标 int ball_y;//球心纵坐标 //球的前一步的y坐标 int ball_previous_y; int ball_x_speed;//球的横向偏移量//可变 int ball_y_speed;//球的纵向偏移量//可变 boolean ball_isRun;//球是否在动 // 控制循环 boolean mbLoop; // 定义SurfaceHolder对象 SurfaceHolder mSurfaceHolder = null; //获得分数 int score; /* 唤醒渐变渲染 */ Shader mRadialGradient = null; //------------------------------------------------------------------------------------------------------// public BallView(Context context) { super(context); // 实例化SurfaceHolder mSurfaceHolder = this.getHolder(); // 添加回调 mSurfaceHolder.addCallback(this); this.setFocusable(true); //获取屏幕宽度和高度 screen_width = BaomingActivity.screenWidth;//320 screen_height = BaomingActivity.screenHeight;//480 //砖的属性 brick_width = screen_width/5;//每块砖宽64 brick_height = screen_height/15;//每块砖高32 //挡板的属性 board_length = screen_width/4;//挡板长度:80比较合适,可以随意修改,但别超过screen_width board_left = (screen_width-board_length)/2;//挡板左侧(可变) board_right = (screen_width+board_length)/2;//挡板右侧(可变) board_thickness = 5;//挡板厚度 board_default_top = 13*screen_height/15;//即435,挡板的top面初始位置 board_alterable_top = board_default_top;//挡板上侧(可变) board_alterable_bottom = board_alterable_top+board_thickness;//挡板下侧(可变) ball_default_x = screen_width/2;//球的初始x坐标 ball_default_y = board_default_top - ball_r;//球的初始y坐标 //球的即时坐标(可变): ball_x = ball_default_x; ball_y = ball_default_y; //球的前一步的y坐标 ball_previous_y = 0; ball_x_speed = ballXorYadd;//球的横向偏移量 ball_y_speed = ballXorYadd;//球的纵向偏移量 mbLoop = true; ball_isRun = false; score=0; brick_exist = new boolean[25]; for (int i = 0; i < 25; i++) { brick_exist[i] = true; } /* 构建RadialGradient对象,设置半径的属性 */ mRadialGradient = new RadialGradient(ball_x, ball_y, ball_r,//球中心坐标x,y,半径r new int[]{Color.WHITE,Color.BLUE,Color.GREEN,Color.RED,Color.YELLOW},//颜色数组 null,//颜色数组中每一种颜色对应的相对位置,为空的话就是平均分布,由中心向外排布 Shader.TileMode.REPEAT);//渲染模式:重复 } public void resetGame(){ ball_isRun = false; score =0;//分数 ball_x_speed = ballXorYadd;//球的横向偏移量 ball_y_speed = ballXorYadd;//球的纵向偏移量 ball_x = screen_width/2;//球心起始横坐标 ball_y = board_default_top - ball_r;//球心起始纵坐标 board_left = (screen_width-board_length)/2;//挡板左侧 board_right = (screen_width+board_length)/2;//挡板右侧 board_alterable_top = board_default_top;//挡板上侧 board_alterable_bottom = board_alterable_top+board_thickness;//挡板下侧 for (int i = 0; i < 25; i++) { brick_exist[i] = true; } } //---------------------------------绘图循环开始---------------------------------- public void run() { while (mbLoop&&!Thread.currentThread().isInterrupted()) { try { Thread.sleep(ball_sleep); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } //球的前一步y坐标 ball_previous_y = ball_y; if (ball_isRun) { ballRunning();// 让小球移动 boardPositionCheck();//检测挡板是否处于“中线”位置,是就随小球上升一步,直至到“上线” hitWallCheck();//墙壁碰撞检测 hitBoardCheck();//挡板碰撞检测 hitBrickCheck();//砖块碰撞检测 } synchronized (mSurfaceHolder) { Draw(); } } } //---------------------------------绘图循环结束---------------------------------- //------------------------------------------------------------------------------ //让小球移动 public void ballRunning() { ball_x += ball_x_speed; ball_y -= ball_y_speed; } //朝左或朝右碰撞后小球水平方向逆向 public void ballLeftOrRightHit() { ball_x_speed *= -1; } //朝上或朝下碰撞后小球竖直方向逆向 public void ballUpOrDownHit() { ball_y_speed *= -1; } public void ballcornerHit() { ball_x_speed *= -1; ball_y_speed *= -1; } public void ballStraightUp() {//功能没实现,这是多余代码 ball_x_speed = 0;//注意在其他地方恢复 ball_y_speed *= -1; } //-------------------墙壁碰撞检测开始------------------------------------- public void hitWallCheck() { // 左碰墙 if (ball_x <= ball_r && ball_y >= ball_r && ball_y <= screen_height) { ballLeftOrRightHit(); // 右碰墙 } if (ball_x >= screen_width - ball_r && //不能写为 else if,因为可能恰好碰到角落。 ball_y >= ball_r && ball_y <= screen_height) { ballLeftOrRightHit(); } // 上碰墙 if (ball_x >= ball_r && ball_x <= screen_width - ball_r && ball_y <= ball_r + brick_height) //、、、、、、、、、、、、、、、25号修改 { ballUpOrDownHit(); } // 下碰墙 if (ball_x >= ball_r && ball_x <= screen_width - ball_r && ball_y >= screen_height-ball_r) { ballUpOrDownHit(); if(score<=10){ score = 0; } else score-=10; } } //-------------------墙壁碰撞检测结束------------------------------------- //-----------------------------挡板碰撞检测开始--------------------------- public void hitBoardCheck() { // 下碰挡板正面 if (ball_x >= ball_r && ball_x <= screen_width - ball_r && //在屏幕内,起码条件 ball_x >= board_left && ball_x <= board_right && //在挡板X域上方 ball_y == board_alterable_top - ball_r &&//球面与挡板相切 ball_previous_y <= board_alterable_top - ball_r //确定球是从上方下落 ) { if(board_alterable_top==board_default_top-boardYadd ){//如果弹簧伸张,挡板位于上线 ballHitBoardlower();//作用:ball_y_move减小;挡板被打下;小球Y向运动反向 } else if(board_alterable_top==board_default_top){//如果弹簧压缩,挡板位于下线 boardHitBallHigher();//作用:ball_y_move增加;挡板弹上;小球Y向运动反向 } } //斜碰挡板右上角//经验证有效 else if(Math.pow(board_right-ball_x, 2)+Math.pow(board_alterable_top-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x>board_right && ball_y<board_alterable_top) { ballcornerHit(); } //斜碰挡板的左上角//经验证有效 else if(Math.pow(board_left-ball_x, 2)+Math.pow(board_alterable_top-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x<board_left && ball_y<board_alterable_top) { ballcornerHit(); } } //-----------------------------挡板碰撞检测结束-------------------------- private void boardHitBallHigher() {//增强 ballUpOrDownHit();//小球Y方向反向,ball_y_speed变为正数 if(ball_y_speed == ballXorYadd ){ ball_y_speed += ballXorYadd;//离开挡板后小球Y方向速度增强 } if( boardYadd > ball_y_speed ){//在线程这一轮,小球上升多少,挡板就上升多少。 board_alterable_top = board_default_top - ball_y_speed; board_alterable_bottom= board_alterable_top+board_thickness;//挡板下层面 } } //检测挡板是否处于“中线”位置,是就随小球上升一步,直至到“上线” private void boardPositionCheck() {//还可直接利用球的位置刷新,board_top与球心相差ball_r if(board_alterable_top < board_default_top && board_alterable_top > board_default_top-boardYadd){ //挡板随球上升 if(board_alterable_top - ball_y_speed >= board_default_top-boardYadd){ board_alterable_top -= ball_y_speed;//挡板上层面 board_alterable_bottom= board_alterable_top+board_thickness;//挡板下层面 } else{ board_alterable_top = board_default_top-boardYadd;//挡板上层面 board_alterable_bottom= board_alterable_top+board_thickness;//挡板下层面 } } } private void ballHitBoardlower() {//减弱 board_alterable_top=board_default_top; board_alterable_bottom=board_default_top+board_thickness;//挡板被打退 ballUpOrDownHit();//小球Y方向反向 if(ball_y_speed==2*ballXorYadd){ ball_y_speed -= ballXorYadd;//小球Y方向速度减弱 } } //砖块碰撞检测开始----------------------------------------------------------- public void hitBrickCheck() { for (int i = 0; i <25 ; i++) { if (brick_exist[i]) { k = i % 5+1;// 1,2,3,4,5循环 j = i / 5+1;// 1,1,1,1,1;2,2,2,2,2,;...;5,5,5,5,5 brick_left = brick_width*(k-1); brick_right = brick_width*k; brick_top = brick_height*j; brick_bottom = brick_height*(j+1); //朝下碰砖的top面 AAAAAAAAAAAAAAAAAAAAA if(ball_x >= brick_left && ball_x <= brick_right && ball_y >= brick_top-ball_r && ball_y < brick_top) { ballUpOrDownHit(); brick_exist[i] = false; score+=4; //朝下正碰2砖中间,i砖右上角检测 if(k!=5 && ball_x == brick_right)//如果不是第5列砖的右侧边 { //如果砖[i+1]存在 if(brick_exist[i+1]){ brick_exist[i+1] = false; score+=4; } } //朝下正碰2砖中间,i砖左上角检测 else if(k!=1 && ball_x == brick_left)//如果不是第1列砖的左侧边 { //如果砖[i-1]存在 if(brick_exist[i-1]){ brick_exist[i-1] = false; score+=4; } } } //朝上碰砖的bottom面 BBBBBBBBBBBBBBBBB else if(ball_x >= brick_left && ball_x <= brick_right && ball_y > brick_bottom&& ball_y <= brick_bottom + ball_r ) { ballUpOrDownHit(); brick_exist[i] = false; score+=4; //朝上正碰2块砖中间--i砖的右下角检测 if(k!=5 && ball_x == brick_right) //如果不是第5列砖的右侧边 { if(brick_exist[i+1]){//如果砖[i+1]存在 brick_exist[i+1] = false; score+=4; } } //朝上正碰2块砖中间--i砖的左下角检测 else if(k!=1 && ball_x == brick_left) //如果不是第1列砖的左侧边 { if(brick_exist[i-1]){//如果砖[i-1]存在 brick_exist[i-1] = false; score+=4; } } } //朝右碰砖的left面CCCCCCCCCCCCCCCCC else if(ball_x >= brick_left -ball_r&&ball_x < brick_left&& ball_y >= brick_top && ball_y <= brick_bottom) { ballLeftOrRightHit(); brick_exist[i] = false; score+=4; //朝右正碰2块砖中间,左下角检测 if(j!=5 && ball_y == brick_bottom)//如果不是第5行砖的下侧边 { if(brick_exist[i+5]){//如果砖[i+5]存在 brick_exist[i+5] = false; score+=4; } } //朝右正碰2块砖中间,左上角检测 else if(j!=1 && ball_y == brick_top)//如果不是第1行砖的上侧边 { if(brick_exist[i-5]){//如果砖[i-5]存在 brick_exist[i-5] = false; score+=4; } } } //朝左碰砖的right面DDDDDDDDDDDDDDDDDD else if(ball_x >= brick_right && ball_x <= brick_right+ball_r&& ball_y >= brick_top && ball_y <= brick_bottom) { ballLeftOrRightHit(); brick_exist[i] = false; score+=4; //朝左正碰2块砖中间,右下角检测 if(j!=5 && ball_y == brick_bottom )//如果不是第5行砖的下侧边 { if(brick_exist[i+5]){//如果砖[i+5]存在 brick_exist[i+5] = false; score+=4; } } //朝左正碰2块砖中间,右上角检测 else if(j!=1 && ball_y == brick_top )//如果不是第1行砖上侧边 { if(brick_exist[i-5]){//如果砖[i-5]存在 brick_exist[i-5] = false; score+=4; } } } ///////////////////////////////////////// //斜碰i砖的左下角EEEEEEEEEEEEEEEEEEEEEEEE else if(( i-1<0||(i-1>=0&&!brick_exist[i-1]) ) && (i+5>=25||(i+5<25&&!brick_exist[i+5]) )&& Math.pow(brick_left-ball_x, 2)+Math.pow(brick_bottom-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x>brick_left-ball_r && ball_x<brick_left && ball_y>brick_bottom && ball_y<brick_bottom+ball_r ) { ballcornerHit(); brick_exist[i] = false; score+=4; } //斜碰i砖的右下角FFFFFFFFFFFFFFFFFFFFFFFFFF else if( (i+1>=25||(i+1<25&&!brick_exist[i+1]) )&& (i+5>=25||(i+5<25&&!brick_exist[i+5]) )&& Math.pow(brick_right-ball_x, 2)+Math.pow(brick_bottom-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x>brick_right&&ball_x<brick_right+ball_r&& ball_y>brick_bottom&&ball_y<brick_bottom+ball_r ) { Log.v("----------", "right bottom hit"+i+":"+brick_exist[i]); ballcornerHit(); brick_exist[i] = false; score+=4; } //斜碰i砖的右上角GGGGGGGGGGGGGGGGGGGGGGGG else if( (i+1>=25||(i+1<25&&!brick_exist[i+1]) )&& (i-5<0||(i-5>0&&!brick_exist[i-5]) )&& Math.pow(brick_right-ball_x, 2)+Math.pow(brick_top-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x>brick_right && ball_x<brick_right+ball_r&& ball_y>brick_top-ball_r && ball_y<brick_top) { ballcornerHit(); brick_exist[i] = false; score+=4; } //斜碰i砖的左上角HHHHHHHHHHHHHHHHHHHHHHHHHH else if((i-1<0||(i-1>=0&&!brick_exist[i-1])) && (i-5<0||(i-5>=0&&!brick_exist[i-5])) && Math.pow(brick_left-ball_x, 2)+Math.pow(brick_top-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x>brick_left-ball_x && ball_x<brick_left && ball_y>brick_top-ball_r && ball_y<brick_top ) { ballcornerHit(); brick_exist[i] = false; score+=4; } }//end if }//end for }//end hitBrickCheck() //砖块碰撞检测结束----------------------------------------------------------- //------------------------------------------ public boolean gameOver(){ int count = 0; for(boolean s:brick_exist){ if(!s){ count++; } } if(count == 25){ return true; }else{ return false; } } //------------------------------------------ //---------------绘图方法开始------------------------ public void Draw() { // 锁定画布,得到canvas Canvas canvas = mSurfaceHolder.lockCanvas(); if (mSurfaceHolder == null || canvas == null) { return; } // 绘图 Paint mPaint = new Paint(); // 设置取消锯齿效果 mPaint.setAntiAlias(true); mPaint.setColor(Color.GREEN); // 绘制矩形--背景 canvas.drawRect(0, 0, screen_width, brick_height-2, mPaint); mPaint.setColor(Color.MAGENTA); // 绘制矩形--背景 canvas.drawRect(0, brick_height-2, screen_width, screen_height, mPaint); mPaint.setColor(Color.RED);//设置字体颜色 mPaint.setTextSize(brick_height-7);//设置字体大小 canvas.drawText("得分:"+score, 0, brick_height-7, mPaint); // 绘制顶层挡板````````````````````````````````````````````````````````25号修改 mPaint.setColor(Color.BLACK);//设置颜色 mPaint.setStrokeWidth(4);//设置粗细 canvas.drawLine(0, brick_height-2, screen_width, brick_height-2, mPaint); for (int i = 0; i <25 ; i++) { if (brick_exist[i]) { k = i % 5+1;// 1,2,3,4,5循环 j = i / 5+1;// 1,1,1,1,1;2,2,2,2,2,;...;5,5,5,5,5 brick_left = brick_width*(k-1); brick_right = brick_width*k; brick_top = brick_height*j; brick_bottom = brick_height*(j+1); mPaint.setStyle(Paint.Style.FILL);// 设置实心画笔 mPaint.setColor(Color.BLACK); canvas.drawRect(brick_left+1, brick_top+1, brick_right-1,brick_bottom-1, mPaint); mPaint.setStyle(Paint.Style.STROKE);// 设置空心画笔 mPaint.setStrokeWidth(2);//设置粗细 mPaint.setColor(Color.RED); canvas.drawRect(brick_left+3, brick_top+3, brick_right-3,brick_bottom-3, mPaint); } } // 设置实心画笔 mPaint.setStyle(Paint.Style.FILL); { mPaint.setShader(mRadialGradient); canvas.drawCircle(ball_x, ball_y, ball_r, mPaint); } Paint mPaint2 = new Paint(); // 设置取消锯齿效果 mPaint2.setAntiAlias(true); // 设置实心画笔 mPaint2.setStyle(Paint.Style.FILL); { mPaint2.setColor(Color.BLACK); /* 绘制矩形挡板 */ canvas.drawRect(board_left, board_alterable_top, board_right, board_alterable_bottom,mPaint2); float board2_bottom = screen_height - 2*ball2_r;//164 float board2_top = board2_bottom - 4;//160 //线段端点坐标数组 float x0 = board_left+(board_right-board_left)/4; float y0 = board_alterable_bottom;//440或者444 float springAdd = (board2_top- board_alterable_bottom)/8;//即2.5或者2:弹簧小线段的y向长度 float springWidth = 5.0f;//弹簧小线段的x向长度 float x1 = x0 - springWidth; float y1 = y0 + springAdd; float x2 = x0 + springWidth; float y2 = y0 + 3*springAdd; float x3 = x1 ; float y3 = y0 + 5*springAdd; float x4 = x2; float y4 = y0 + 7*springAdd; float x5 = x0 ; float y5 = board2_top;//即460 float between_spring = (board_right-board_left)/2; float pts[] = { x0,y0,x1,y1, x1,y1,x2,y2, x2,y2,x3,y3, x3,y3,x4,y4, x4,y4,x5,y5}; float pts2[] = {x0+between_spring,y0, x1+between_spring,y1, x1+between_spring,y1, x2+between_spring,y2, x2+between_spring,y2, x3+between_spring,y3, x3+between_spring,y3, x4+between_spring,y4, x4+between_spring,y4, x5+between_spring,y5}; mPaint2.setStrokeWidth(2);//设置弹簧粗细 //绘制2个弹簧 canvas.drawLines(pts, mPaint2); canvas.drawLines(pts2, mPaint2); //绘制下层挡板 canvas.drawRect(board_left, board2_top, board_right, board2_bottom,mPaint2); mPaint2.setColor(Color.BLACK);// // 绘制最下面的两个“轮子”(圆心x,圆心y,半径r,p) canvas.drawCircle(board_left+ball2_r, screen_height-ball2_r, ball2_r, mPaint2);//圆 canvas.drawCircle(board_right-ball2_r, screen_height-ball2_r, ball2_r, mPaint2); mPaint2.setColor(Color.WHITE);// }//实心画笔mPaint2结束 if(gameOver()){ // mbLoop = false;//注释掉的话GAME OVER后也可重启 ball_isRun = false; mPaint2.setColor(Color.BLACK);//设置字体颜色 mPaint2.setTextSize(40.0f);//设置字体大小 canvas.drawText("GAME OVER", screen_width/32+40, screen_height/16*9-70, mPaint2); mPaint2.setTextSize(20.0f);//设置字体大小 canvas.drawText("Press \"MENU\" button to restart,", screen_width/32, //320/32=10 screen_height/16*9, //480/16=30,30*9=270 mPaint2); canvas.drawText("Press \"BACK\" button to exit.", screen_width/32, //320/32=10 screen_height/16*10, //480/16=30,30*10=300 mPaint2); } // 绘制后解锁,绘制后必须解锁才能显示 mSurfaceHolder.unlockCanvasAndPost(canvas); }// end of Draw() //---------------------绘图方法结束----------------------------------------------- // 在surface的大小发生改变时激发 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } // 在surface创建时激发 public void surfaceCreated(SurfaceHolder holder) { new Thread(this).start();// 开启绘图线程 } // 在surface销毁时激发 public void surfaceDestroyed(SurfaceHolder holder) { // 停止循环 mbLoop = false; } } 能否回答的详细一点,学的时间短,求帮忙
所做Android打砖块代码其中 出错 求教
下面是代码 可其中出现了一个错误(做了标记),不知道怎么解决,可否有高手帮我看看,能不能稍作修改一下,做成正确的。 就是这句错了 myview = new BallView(this); package sen.tan; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; public class dazhuankuaiActivity extends Activity { BallView myview; public static int screenWidth ; public static int screenHeight; private TextView textview; Button kaishi,jieshu,guanyu; ImageView image; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); String string = "欢迎进入疯狂打砖块游戏"; image = (ImageView) this.findViewById(R.id.image); image.setImageResource(R.drawable.img1); textview =(TextView) this.findViewById(R.id.textview); textview.setTextSize(20); textview.setTextColor(Color.GREEN); textview.setBackgroundColor(Color.RED); textview.setText(string); kaishi=(Button)findViewById(R.id.button1); guanyu=(Button)findViewById(R.id.button2); jieshu=(Button)findViewById(R.id.button3); kaishi.setWidth(250); guanyu.setWidth(200); jieshu.setWidth(150); kaishi.setTextSize(35); guanyu.setTextSize(29); jieshu.setTextSize(24); jieshu.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v) { dazhuankuaiActivity.this.finish(); } }); guanyu.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v){ textview.setText("本游戏由xxx制作,此游戏控制左右按键,来回移动挡板,不让小球掉落,当小球把上方砖块全部打完时,游戏胜利"); } }); kaishi.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v){ DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); screenWidth = dm.widthPixels; screenHeight = dm.heightPixels; setTitle("宽"+screenWidth+" 高"+screenHeight); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); `myview = new BallView(this);` //错误在这里 setContentView(myview); } public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_MENU: myview.resetGame(); break; case KeyEvent.KEYCODE_DPAD_CENTER: myview.ball_isRun = !myview.ball_isRun; break; case KeyEvent.KEYCODE_DPAD_LEFT: if(myview.ball_isRun){ if(myview.board_left<=myview.board_x_move) { myview.board_left=0; myview.board_right=myview.board_length; }else{ myview.board_left-=myview.board_x_move; myview.board_right-=myview.board_x_move;} } break; case KeyEvent.KEYCODE_DPAD_RIGHT: if(myview.ball_isRun){ if(screenWidth-myview.board_right<=myview.board_x_move ) { myview.board_left=screenWidth-myview.board_length; myview.board_right=screenWidth; }else{ myview.board_left+=myview.board_x_move; myview.board_right+=myview.board_x_move; } } break; case KeyEvent.KEYCODE_DPAD_UP: if(myview.ball_isRun){ if( myview.board_alterable_top==myview.board_default_top) { myview.board_alterable_top-=myview.boardYadd; myview.board_alterable_bottom-=myview.boardYadd; } } break; case KeyEvent.KEYCODE_DPAD_DOWN: if(myview.ball_isRun){ if( myview.board_alterable_top==myview.board_default_top-myview.boardYadd ) { myview.board_alterable_top=myview.board_default_top; myview.board_alterable_bottom=myview.board_alterable_top+myview.board_thickness; } } break; case KeyEvent.KEYCODE_BACK: dazhuankuaiActivity.this.finish(); break; }//end switch return false; } //按键弹起事件 } ); } } package sen.tan; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RadialGradient; import android.graphics.Shader; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; public class BallView extends SurfaceView implements SurfaceHolder.Callback, Runnable { //线程延时控制 final int ball_sleep=1;//毫秒,延时越大,球速越慢 final int ball_r= 8;//小球半径 final float ball2_r= 8;//底下滚珠小球半径 final int ballXorYadd = 4;//小球的基本位移。测试可行值:2,4 //获取屏幕宽度和高度 int screen_width;//320; int screen_height;//480; //砖的属性 int brick_width;//每块砖宽 int brick_height;//每块砖高 boolean brick_exist[];//砖是否存在 int k ;// 列//到for循环里才初始化 int j ;// 行 int brick_left = brick_width*(k-1);//到判断语句才初始化 int brick_right = brick_width*k; int brick_top = brick_height*j; int brick_bottom = brick_height*(j+1); //挡板的属性 int board_length;//挡板长度:80比较合适,可以随意修改,但别超过screen_width final int boardYadd = 16;//按上下键时挡板y方向位移量。经验证4、8、16可以,12不行 final int board_x_move = 30;//挡板x方向位移量:可以随意自定义 int board_left;//挡板左侧(可变) int board_right;//挡板右侧(可变) int board_thickness;//挡板厚度 int board_default_top;//即435,挡板的top面初始位置 int board_alterable_top;//挡板上侧(可变) int board_alterable_bottom;//挡板下侧(可变) int ball_default_x;//球的初始x坐标 int ball_default_y;//球的初始y坐标 //球的即时坐标(可变): int ball_x;//球心横坐标 int ball_y;//球心纵坐标 //球的前一步的y坐标 int ball_previous_y; int ball_x_speed;//球的横向偏移量//可变 int ball_y_speed;//球的纵向偏移量//可变 boolean ball_isRun;//球是否在动 // 控制循环 boolean mbLoop; // 定义SurfaceHolder对象 SurfaceHolder mSurfaceHolder = null; //获得分数 int score; /* 唤醒渐变渲染 */ Shader mRadialGradient = null; //------------------------------------------------------------------------------------------------------// public BallView(Context context) { super(context); // 实例化SurfaceHolder mSurfaceHolder = this.getHolder(); // 添加回调 mSurfaceHolder.addCallback(this); this.setFocusable(true); //获取屏幕宽度和高度 screen_width = dazhuankuaiActivity.screenWidth;//320 screen_height = dazhuankuaiActivity.screenHeight;//480 //砖的属性 brick_width = screen_width/5;//每块砖宽64 brick_height = screen_height/15;//每块砖高32 //挡板的属性 board_length = screen_width/4;//挡板长度:80比较合适,可以随意修改,但别超过screen_width board_left = (screen_width-board_length)/2;//挡板左侧(可变) board_right = (screen_width+board_length)/2;//挡板右侧(可变) board_thickness = 5;//挡板厚度 board_default_top = 13*screen_height/15;//即435,挡板的top面初始位置 board_alterable_top = board_default_top;//挡板上侧(可变) board_alterable_bottom = board_alterable_top+board_thickness;//挡板下侧(可变) ball_default_x = screen_width/2;//球的初始x坐标 ball_default_y = board_default_top - ball_r;//球的初始y坐标 //球的即时坐标(可变): ball_x = ball_default_x; ball_y = ball_default_y; //球的前一步的y坐标 ball_previous_y = 0; ball_x_speed = ballXorYadd;//球的横向偏移量 ball_y_speed = ballXorYadd;//球的纵向偏移量 mbLoop = true; ball_isRun = false; score=0; brick_exist = new boolean[25]; for (int i = 0; i < 25; i++) { brick_exist[i] = true; } /* 构建RadialGradient对象,设置半径的属性 */ mRadialGradient = new RadialGradient(ball_x, ball_y, ball_r,//球中心坐标x,y,半径r new int[]{Color.WHITE,Color.BLUE,Color.GREEN,Color.RED,Color.YELLOW},//颜色数组 null,//颜色数组中每一种颜色对应的相对位置,为空的话就是平均分布,由中心向外排布 Shader.TileMode.REPEAT);//渲染模式:重复 } public void resetGame(){ ball_isRun = false; score =0;//分数 ball_x_speed = ballXorYadd;//球的横向偏移量 ball_y_speed = ballXorYadd;//球的纵向偏移量 ball_x = screen_width/2;//球心起始横坐标 ball_y = board_default_top - ball_r;//球心起始纵坐标 board_left = (screen_width-board_length)/2;//挡板左侧 board_right = (screen_width+board_length)/2;//挡板右侧 board_alterable_top = board_default_top;//挡板上侧 board_alterable_bottom = board_alterable_top+board_thickness;//挡板下侧 for (int i = 0; i < 25; i++) { brick_exist[i] = true; } } //---------------------------------绘图循环开始---------------------------------- public void run() { while (mbLoop&&!Thread.currentThread().isInterrupted()) { try { Thread.sleep(ball_sleep); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } //球的前一步y坐标 ball_previous_y = ball_y; if (ball_isRun) { ballRunning();// 让小球移动 boardPositionCheck();//检测挡板是否处于“中线”位置,是就随小球上升一步,直至到“上线” hitWallCheck();//墙壁碰撞检测 hitBoardCheck();//挡板碰撞检测 hitBrickCheck();//砖块碰撞检测 } synchronized (mSurfaceHolder) { Draw(); } } } //---------------------------------绘图循环结束---------------------------------- //------------------------------------------------------------------------------ //让小球移动 public void ballRunning() { ball_x += ball_x_speed; ball_y -= ball_y_speed; } //朝左或朝右碰撞后小球水平方向逆向 public void ballLeftOrRightHit() { ball_x_speed *= -1; } //朝上或朝下碰撞后小球竖直方向逆向 public void ballUpOrDownHit() { ball_y_speed *= -1; } public void ballcornerHit() { ball_x_speed *= -1; ball_y_speed *= -1; } public void ballStraightUp() {//功能没实现,这是多余代码 ball_x_speed = 0;//注意在其他地方恢复 ball_y_speed *= -1; } //-------------------墙壁碰撞检测开始------------------------------------- public void hitWallCheck() { // 左碰墙 if (ball_x <= ball_r && ball_y >= ball_r && ball_y <= screen_height) { ballLeftOrRightHit(); // 右碰墙 } if (ball_x >= screen_width - ball_r && //不能写为 else if,因为可能恰好碰到角落。 ball_y >= ball_r && ball_y <= screen_height) { ballLeftOrRightHit(); } // 上碰墙 if (ball_x >= ball_r && ball_x <= screen_width - ball_r && ball_y <= ball_r + brick_height) //、、、、、、、、、、、、、、、25号修改 { ballUpOrDownHit(); } // 下碰墙 if (ball_x >= ball_r && ball_x <= screen_width - ball_r && ball_y >= screen_height-ball_r) { ballUpOrDownHit(); if(score<=10){ score = 0; } else score-=10; } } //-------------------墙壁碰撞检测结束------------------------------------- //-----------------------------挡板碰撞检测开始--------------------------- public void hitBoardCheck() { // 下碰挡板正面 if (ball_x >= ball_r && ball_x <= screen_width - ball_r && //在屏幕内,起码条件 ball_x >= board_left && ball_x <= board_right && //在挡板X域上方 ball_y == board_alterable_top - ball_r &&//球面与挡板相切 ball_previous_y <= board_alterable_top - ball_r //确定球是从上方下落 ) { if(board_alterable_top==board_default_top-boardYadd ){//如果弹簧伸张,挡板位于上线 ballHitBoardlower();//作用:ball_y_move减小;挡板被打下;小球Y向运动反向 } else if(board_alterable_top==board_default_top){//如果弹簧压缩,挡板位于下线 boardHitBallHigher();//作用:ball_y_move增加;挡板弹上;小球Y向运动反向 } } //斜碰挡板右上角//经验证有效 else if(Math.pow(board_right-ball_x, 2)+Math.pow(board_alterable_top-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x>board_right && ball_y<board_alterable_top) { ballcornerHit(); } //斜碰挡板的左上角//经验证有效 else if(Math.pow(board_left-ball_x, 2)+Math.pow(board_alterable_top-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x<board_left && ball_y<board_alterable_top) { ballcornerHit(); } } //-----------------------------挡板碰撞检测结束-------------------------- private void boardHitBallHigher() {//增强 ballUpOrDownHit();//小球Y方向反向,ball_y_speed变为正数 if(ball_y_speed == ballXorYadd ){ ball_y_speed += ballXorYadd;//离开挡板后小球Y方向速度增强 } if( boardYadd > ball_y_speed ){//在线程这一轮,小球上升多少,挡板就上升多少。 board_alterable_top = board_default_top - ball_y_speed; board_alterable_bottom= board_alterable_top+board_thickness;//挡板下层面 } } //检测挡板是否处于“中线”位置,是就随小球上升一步,直至到“上线” private void boardPositionCheck() {//还可直接利用球的位置刷新,board_top与球心相差ball_r if(board_alterable_top < board_default_top && board_alterable_top > board_default_top-boardYadd){ //挡板随球上升 if(board_alterable_top - ball_y_speed >= board_default_top-boardYadd){ board_alterable_top -= ball_y_speed;//挡板上层面 board_alterable_bottom= board_alterable_top+board_thickness;//挡板下层面 } else{ board_alterable_top = board_default_top-boardYadd;//挡板上层面 board_alterable_bottom= board_alterable_top+board_thickness;//挡板下层面 } } } private void ballHitBoardlower() {//减弱 board_alterable_top=board_default_top; board_alterable_bottom=board_default_top+board_thickness;//挡板被打退 ballUpOrDownHit();//小球Y方向反向 if(ball_y_speed==2*ballXorYadd){ ball_y_speed -= ballXorYadd;//小球Y方向速度减弱 } } //砖块碰撞检测开始----------------------------------------------------------- public void hitBrickCheck() { for (int i = 0; i <25 ; i++) { if (brick_exist[i]) { k = i % 5+1;// 1,2,3,4,5循环 j = i / 5+1;// 1,1,1,1,1;2,2,2,2,2,;...;5,5,5,5,5 brick_left = brick_width*(k-1); brick_right = brick_width*k; brick_top = brick_height*j; brick_bottom = brick_height*(j+1); //朝下碰砖的top面 AAAAAAAAAAAAAAAAAAAAA if(ball_x >= brick_left && ball_x <= brick_right && ball_y >= brick_top-ball_r && ball_y < brick_top) { ballUpOrDownHit(); brick_exist[i] = false; score+=4; //朝下正碰2砖中间,i砖右上角检测 if(k!=5 && ball_x == brick_right)//如果不是第5列砖的右侧边 { //如果砖[i+1]存在 if(brick_exist[i+1]){ brick_exist[i+1] = false; score+=4; } } //朝下正碰2砖中间,i砖左上角检测 else if(k!=1 && ball_x == brick_left)//如果不是第1列砖的左侧边 { //如果砖[i-1]存在 if(brick_exist[i-1]){ brick_exist[i-1] = false; score+=4; } } } //朝上碰砖的bottom面 BBBBBBBBBBBBBBBBB else if(ball_x >= brick_left && ball_x <= brick_right && ball_y > brick_bottom&& ball_y <= brick_bottom + ball_r ) { ballUpOrDownHit(); brick_exist[i] = false; score+=4; //朝上正碰2块砖中间--i砖的右下角检测 if(k!=5 && ball_x == brick_right) //如果不是第5列砖的右侧边 { if(brick_exist[i+1]){//如果砖[i+1]存在 brick_exist[i+1] = false; score+=4; } } //朝上正碰2块砖中间--i砖的左下角检测 else if(k!=1 && ball_x == brick_left) //如果不是第1列砖的左侧边 { if(brick_exist[i-1]){//如果砖[i-1]存在 brick_exist[i-1] = false; score+=4; } } } //朝右碰砖的left面CCCCCCCCCCCCCCCCC else if(ball_x >= brick_left -ball_r&&ball_x < brick_left&& ball_y >= brick_top && ball_y <= brick_bottom) { ballLeftOrRightHit(); brick_exist[i] = false; score+=4; //朝右正碰2块砖中间,左下角检测 if(j!=5 && ball_y == brick_bottom)//如果不是第5行砖的下侧边 { if(brick_exist[i+5]){//如果砖[i+5]存在 brick_exist[i+5] = false; score+=4; } } //朝右正碰2块砖中间,左上角检测 else if(j!=1 && ball_y == brick_top)//如果不是第1行砖的上侧边 { if(brick_exist[i-5]){//如果砖[i-5]存在 brick_exist[i-5] = false; score+=4; } } } //朝左碰砖的right面DDDDDDDDDDDDDDDDDD else if(ball_x >= brick_right && ball_x <= brick_right+ball_r&& ball_y >= brick_top && ball_y <= brick_bottom) { ballLeftOrRightHit(); brick_exist[i] = false; score+=4; //朝左正碰2块砖中间,右下角检测 if(j!=5 && ball_y == brick_bottom )//如果不是第5行砖的下侧边 { if(brick_exist[i+5]){//如果砖[i+5]存在 brick_exist[i+5] = false; score+=4; } } //朝左正碰2块砖中间,右上角检测 else if(j!=1 && ball_y == brick_top )//如果不是第1行砖上侧边 { if(brick_exist[i-5]){//如果砖[i-5]存在 brick_exist[i-5] = false; score+=4; } } } ///////////////////////////////////////// //斜碰i砖的左下角EEEEEEEEEEEEEEEEEEEEEEEE else if(( i-1<0||(i-1>=0&&!brick_exist[i-1]) ) && (i+5>=25||(i+5<25&&!brick_exist[i+5]) )&& Math.pow(brick_left-ball_x, 2)+Math.pow(brick_bottom-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x>brick_left-ball_r && ball_x<brick_left && ball_y>brick_bottom && ball_y<brick_bottom+ball_r ) { ballcornerHit(); brick_exist[i] = false; score+=4; } //斜碰i砖的右下角FFFFFFFFFFFFFFFFFFFFFFFFFF else if( (i+1>=25||(i+1<25&&!brick_exist[i+1]) )&& (i+5>=25||(i+5<25&&!brick_exist[i+5]) )&& Math.pow(brick_right-ball_x, 2)+Math.pow(brick_bottom-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x>brick_right&&ball_x<brick_right+ball_r&& ball_y>brick_bottom&&ball_y<brick_bottom+ball_r ) { Log.v("----------", "right bottom hit"+i+":"+brick_exist[i]); ballcornerHit(); brick_exist[i] = false; score+=4; } //斜碰i砖的右上角GGGGGGGGGGGGGGGGGGGGGGGG else if( (i+1>=25||(i+1<25&&!brick_exist[i+1]) )&& (i-5<0||(i-5>0&&!brick_exist[i-5]) )&& Math.pow(brick_right-ball_x, 2)+Math.pow(brick_top-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x>brick_right && ball_x<brick_right+ball_r&& ball_y>brick_top-ball_r && ball_y<brick_top) { ballcornerHit(); brick_exist[i] = false; score+=4; } //斜碰i砖的左上角HHHHHHHHHHHHHHHHHHHHHHHHHH else if((i-1<0||(i-1>=0&&!brick_exist[i-1])) && (i-5<0||(i-5>=0&&!brick_exist[i-5])) && Math.pow(brick_left-ball_x, 2)+Math.pow(brick_top-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x>brick_left-ball_x && ball_x<brick_left && ball_y>brick_top-ball_r && ball_y<brick_top ) { ballcornerHit(); brick_exist[i] = false; score+=4; } }//end if }//end for }//end hitBrickCheck() //砖块碰撞检测结束----------------------------------------------------------- //------------------------------------------ public boolean gameOver(){ int count = 0; for(boolean s:brick_exist){ if(!s){ count++; } } if(count == 25){ return true; }else{ return false; } } //------------------------------------------ //---------------绘图方法开始------------------------ public void Draw() { // 锁定画布,得到canvas Canvas canvas = mSurfaceHolder.lockCanvas(); if (mSurfaceHolder == null || canvas == null) { return; } // 绘图 Paint mPaint = new Paint(); // 设置取消锯齿效果 mPaint.setAntiAlias(true); mPaint.setColor(Color.BLACK); // 绘制矩形--背景 canvas.drawRect(0, 0, screen_width, brick_height-2, mPaint); mPaint.setColor(Color.GREEN); // 绘制矩形--背景 canvas.drawRect(0, brick_height-2, screen_width, screen_height, mPaint); mPaint.setColor(Color.RED);//设置字体颜色 mPaint.setTextSize(brick_height-7);//设置字体大小 canvas.drawText("得分:"+score, 0, brick_height-7, mPaint); // 绘制顶层挡板````````````````````````````````````````````````````````25号修改 mPaint.setColor(Color.BLACK);//设置颜色 mPaint.setStrokeWidth(4);//设置粗细 canvas.drawLine(0, brick_height-2, screen_width, brick_height-2, mPaint); for (int i = 0; i <25 ; i++) { if (brick_exist[i]) { k = i % 5+1;// 1,2,3,4,5循环 j = i / 5+1;// 1,1,1,1,1;2,2,2,2,2,;...;5,5,5,5,5 brick_left = brick_width*(k-1); brick_right = brick_width*k; brick_top = brick_height*j; brick_bottom = brick_height*(j+1); mPaint.setStyle(Paint.Style.FILL);// 设置实心画笔 mPaint.setColor(Color.YELLOW); canvas.drawRect(brick_left+1, brick_top+1, brick_right-1,brick_bottom-1, mPaint); mPaint.setStyle(Paint.Style.STROKE);// 设置空心画笔 mPaint.setStrokeWidth(2);//设置粗细 mPaint.setColor(Color.BLUE); canvas.drawRect(brick_left+3, brick_top+3, brick_right-3,brick_bottom-3, mPaint); } } // 设置实心画笔 mPaint.setStyle(Paint.Style.FILL); { mPaint.setShader(mRadialGradient); canvas.drawCircle(ball_x, ball_y, ball_r, mPaint); } Paint mPaint2 = new Paint(); // 设置取消锯齿效果 mPaint2.setAntiAlias(true); // 设置实心画笔 mPaint2.setStyle(Paint.Style.FILL); { mPaint2.setColor(Color.BLACK); /* 绘制矩形挡板 */ canvas.drawRect(board_left, board_alterable_top, board_right, board_alterable_bottom,mPaint2); float board2_bottom = screen_height - 2*ball2_r;//164 float board2_top = board2_bottom - 4;//160 //线段端点坐标数组 float x0 = board_left+(board_right-board_left)/4; float y0 = board_alterable_bottom;//440或者444 float springAdd = (board2_top- board_alterable_bottom)/8;//即2.5或者2:弹簧小线段的y向长度 float springWidth = 5.0f;//弹簧小线段的x向长度 float x1 = x0 - springWidth; float y1 = y0 + springAdd; float x2 = x0 + springWidth; float y2 = y0 + 3*springAdd; float x3 = x1 ; float y3 = y0 + 5*springAdd; float x4 = x2; float y4 = y0 + 7*springAdd; float x5 = x0 ; float y5 = board2_top;//即460 float between_spring = (board_right-board_left)/2; float pts[] = { x0,y0,x1,y1, x1,y1,x2,y2, x2,y2,x3,y3, x3,y3,x4,y4, x4,y4,x5,y5}; float pts2[] = {x0+between_spring,y0, x1+between_spring,y1, x1+between_spring,y1, x2+between_spring,y2, x2+between_spring,y2, x3+between_spring,y3, x3+between_spring,y3, x4+between_spring,y4, x4+between_spring,y4, x5+between_spring,y5}; mPaint2.setStrokeWidth(2);//设置弹簧粗细 //绘制2个弹簧 canvas.drawLines(pts, mPaint2); canvas.drawLines(pts2, mPaint2); //绘制下层挡板 canvas.drawRect(board_left, board2_top, board_right, board2_bottom,mPaint2); mPaint2.setColor(Color.BLACK);// // 绘制最下面的两个“轮子”(圆心x,圆心y,半径r,p) canvas.drawCircle(board_left+ball2_r, screen_height-ball2_r, ball2_r, mPaint2);//圆 canvas.drawCircle(board_right-ball2_r, screen_height-ball2_r, ball2_r, mPaint2); mPaint2.setColor(Color.WHITE);// canvas.drawPoint(board_left+ball2_r, screen_height-ball2_r, mPaint2);//绘制左轮轮心 canvas.drawPoint(board_right-ball2_r, screen_height-ball2_r, mPaint2);//绘制右轮轮心 }//实心画笔mPaint2结束 if(gameOver()){ // mbLoop = false;//注释掉的话GAME OVER后也可重启 ball_isRun = false; mPaint2.setColor(Color.BLACK);//设置字体颜色 mPaint2.setTextSize(40.0f);//设置字体大小 canvas.drawText("GAME OVER", screen_width/32+40, screen_height/16*9-70, mPaint2); mPaint2.setTextSize(20.0f);//设置字体大小 canvas.drawText("Press \"MENU\" button to restart,", screen_width/32, //320/32=10 screen_height/16*9, //480/16=30,30*9=270 mPaint2); canvas.drawText("Press \"BACK\" button to exit.", screen_width/32, //320/32=10 screen_height/16*10, //480/16=30,30*10=300 mPaint2); } // 绘制后解锁,绘制后必须解锁才能显示 mSurfaceHolder.unlockCanvasAndPost(canvas); }// end of Draw() //---------------------绘图方法结束----------------------------------------------- // 在surface的大小发生改变时激发 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } // 在surface创建时激发 public void surfaceCreated(SurfaceHolder holder) { new Thread(this).start();// 开启绘图线程 } // 在surface销毁时激发 public void surfaceDestroyed(SurfaceHolder holder) { // 停止循环 mbLoop = false; } } 下个界面的代码是 package ab.cc; import android.app.Activity; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.Window; import android.view.WindowManager; public class BaomingActivity extends Activity { BallView myView; static int screenWidth; static int screenHeight; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* 定义DisplayMetrics对象 */ DisplayMetrics dm = new DisplayMetrics(); /* 取得窗口属性 */ getWindowManager().getDefaultDisplay().getMetrics(dm); /* 窗口的宽度 */ screenWidth = dm.widthPixels; /* 窗口的高度 */ screenHeight = dm.heightPixels; // setTitle("宽"+screenWidth+" 高"+screenHeight); /* 设置为无标题栏 */ requestWindowFeature(Window.FEATURE_NO_TITLE); /* 设置为全屏模式 */ getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); myView = new BallView(this); //设置显示GameSurfaceView视图 setContentView(myView); }//end of onCreate() //触笔事件 public boolean onTouchEvent(MotionEvent event) { return true; } //按键按下事件 public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { //菜单按键-设为初始菜单 case KeyEvent.KEYCODE_MENU: myView.resetGame(); //重新开始 break; //中间按键 case KeyEvent.KEYCODE_DPAD_CENTER: myView.ball_isRun = !myView.ball_isRun;//开始//暂停 break; //左方向键 case KeyEvent.KEYCODE_DPAD_LEFT: if(myView.ball_isRun){ if(myView.board_left<=myView.board_x_move) { myView.board_left=0; myView.board_right=myView.board_length; }else{ myView.board_left-=myView.board_x_move; myView.board_right-=myView.board_x_move;} } break; //右方向键 case KeyEvent.KEYCODE_DPAD_RIGHT: if(myView.ball_isRun){ if(screenWidth-myView.board_right<=myView.board_x_move ) { myView.board_left=screenWidth-myView.board_length; myView.board_right=screenWidth; }else{ myView.board_left+=myView.board_x_move; myView.board_right+=myView.board_x_move; } } break; //上方向键 case KeyEvent.KEYCODE_DPAD_UP: if(myView.ball_isRun){ if( myView.board_alterable_top==myView.board_default_top) { myView.board_alterable_top-=myView.boardYadd; myView.board_alterable_bottom-=myView.boardYadd; } } break; //下方向键 case KeyEvent.KEYCODE_DPAD_DOWN: if(myView.ball_isRun){ if( myView.board_alterable_top==myView.board_default_top-myView.boardYadd ) { myView.board_alterable_top=myView.board_default_top; myView.board_alterable_bottom=myView.board_alterable_top+myView.board_thickness; } } break; //返回键 case KeyEvent.KEYCODE_BACK: this.finish(); break; }//end switch return false; } //按键弹起事件 public boolean onKeyUp(int keyCode, KeyEvent event) { return true; } public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { return true; } }
Android拍视频预览的界面被拉伸
最近 Android 需要做一个拍视频保存然后上传的功能,基本功能实现了,但是有一个小 bug,就是预览的时候界面明显被拉长了,但是各种预览设置的参数也都试过了,都没有用,来请教一下。 #代码如下: ##1. Activity ``` public class RecordActivity extends AppCompatActivity implements SurfaceHolder.Callback { private SurfaceView mSurfaceView; private SurfaceHolder mSurfaceHolder; private Button btnStartStop; private boolean isRecording = false; // 标记是否已经在录制 private MediaRecorder mRecorder; // 音视频录制类 private Camera mCamera = null; // 相机 private List<Camera.Size> mSupportedPreviewSizes = null; private Camera.Size mPreviewSize; private Camera.Size mSize = null;// 相机的尺寸 private int mCameraFacing = Camera.CameraInfo.CAMERA_FACING_BACK; // 默认后置摄像头 private static final SparseIntArray orientations = new SparseIntArray(); // 手机旋转对应的调整角度 static { orientations.append(Surface.ROTATION_0, 90); orientations.append(Surface.ROTATION_90, 0); orientations.append(Surface.ROTATION_180, 270); orientations.append(Surface.ROTATION_270, 180); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initWindow(); setContentView(R.layout.activity_record); initViews(); } /** * 初始化窗口 */ private void initWindow() { requestWindowFeature(Window.FEATURE_NO_TITLE); // 去掉标题栏 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // 设置全屏 // 设置竖屏显示 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // 选择支持半透明模式,在有 surfaceView 的 activity 中使用。 getWindow().setFormat(PixelFormat.TRANSLUCENT); } /** * 视图对象初始化 */ private void initViews() { mSurfaceView = (SurfaceView) findViewById(R.id.surfaceview); btnStartStop = (Button) findViewById(R.id.btnStartStop); btnStartStop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!isRecording) { startRecord(); } else { stopRecord(); } } }); SurfaceHolder holder = mSurfaceView.getHolder(); // 取得holder holder.setFormat(PixelFormat.TRANSPARENT); holder.setKeepScreenOn(true); holder.addCallback(this); // holder加入回调接口 } /** * 初始化相机 */ private void initCamera() { /** * 默认打开后置摄像头 */ if (Camera.getNumberOfCameras() == 2) { mCamera = Camera.open(mCameraFacing); } else { mCamera = Camera.open(); } CameraSizeComparator sizeComparator = new CameraSizeComparator(); Camera.Parameters parameters = mCamera.getParameters(); if (mSize == null) { mSupportedPreviewSizes = parameters.getSupportedPreviewSizes(); Collections.sort(mSupportedPreviewSizes, sizeComparator); for (int num = 0; num < mSupportedPreviewSizes.size(); num++) { Camera.Size size = mSupportedPreviewSizes.get(num); if (size.width >= 1000 && size.height >= 1000) { this.mSize = size; break; } } mSize = mSupportedPreviewSizes.get(0); /** * 增加对聚焦模式的判断 */ List<String> focusModesList = parameters.getSupportedFocusModes(); if (focusModesList.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) { parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO); } else if (focusModesList.contains(Camera.Parameters.FOCUS_MODE_AUTO)) { parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO); } mCamera.setParameters(parameters); } int rotation = getWindowManager().getDefaultDisplay().getRotation(); int orientation = orientations.get(rotation); mCamera.setDisplayOrientation(orientation); } @Override protected void onResume() { super.onResume(); initCamera(); } @Override public void onPause() { releaseCamera(); super.onPause(); } /** * 开始录制 */ private void startRecord() { if (mRecorder == null) { mRecorder = new MediaRecorder(); // 创建MediaRecorder } if (mCamera != null) { mCamera.stopPreview(); mCamera.unlock(); mRecorder.setCamera(mCamera); } try { // 设置音频采集方式 mRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER); // 设置视频的采集方式 mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); /* mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); // 设置文件的输出格式 mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); // 设置audio的编码格式 mRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264); // 设置video的编码格式 mRecorder.setVideoEncodingBitRate(10 * 1024 * 1024); // 设置录制的视频编码比特率 mRecorder.setVideoFrameRate(30); // 设置录制的视频帧率 mRecorder.setVideoSize(1920, 1080); // 设置相机分辨率 */ // 设置要捕获的视频的宽度和高度 // mSurfaceHolder.setFixedSize(optimalSize.width, optimalSize.height); mRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH)); // 设置记录会话的最大持续时间(毫秒) mRecorder.setMaxDuration(180 * 1000); mRecorder.setPreviewDisplay(mSurfaceHolder.getSurface()); /** * 获取外部路径,然后将视频保存进去 */ String path = Environment.getExternalStorageDirectory().getPath(); if (path != null) { File dir = new File(path + "/crafts_videos"); if (!dir.exists()) { dir.mkdir(); } /** * 将 currentTimeMillis() 作为文件名 */ path = dir + "/" + System.currentTimeMillis() + ".mp4"; mRecorder.setOutputFile(path); //设置输出文件的路径 mRecorder.prepare(); //准备录制 mRecorder.start(); //开始录制 isRecording = true; btnStartStop.setText("停止"); } } catch (Exception e) { e.printStackTrace(); } } /** * 停止录制 */ private void stopRecord() { try { mRecorder.stop(); // 停止录制 mRecorder.reset(); // 重置 btnStartStop.setText("开始"); } catch (Exception e) { e.printStackTrace(); } isRecording = false; } /** * 释放 MediaRecorder */ private void releaseMediaRecorder() { if (mRecorder != null) { mRecorder.release(); mRecorder = null; } } /** * 释放相机资源 */ private void releaseCamera() { try { if (mCamera != null) { mCamera.stopPreview(); mCamera.setPreviewCallback(null); mCamera.unlock(); mCamera.release(); } } catch (RuntimeException e) { } finally { mCamera = null; } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // 将holder,这个holder为开始在onCreate里面取得的holder,将它赋给mSurfaceHolder mSurfaceHolder = holder; if (mCamera == null) { return; } try { //设置显示 mCamera.setPreviewDisplay(holder); mCamera.startPreview(); } catch (Exception e) { e.printStackTrace(); releaseCamera(); finish(); } } @Override public void surfaceCreated(SurfaceHolder holder) { // 将holder,这个holder为开始在onCreate里面取得的holder,将它赋给mSurfaceHolder mSurfaceHolder = holder; try { mCamera.setPreviewDisplay(mSurfaceHolder); mCamera.startPreview(); } catch (IOException e) { e.printStackTrace(); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { // surfaceDestroyed的时候同时对象设置为null if (isRecording && mCamera != null) { mCamera.lock(); } mSurfaceView = null; mSurfaceHolder = null; releaseMediaRecorder(); releaseCamera(); } private class CameraSizeComparator implements Comparator<Camera.Size> { public int compare(Camera.Size lhs, Camera.Size rhs) { if (lhs.width == rhs.width) { return 0; } else if (lhs.width > rhs.width) { return 1; } else { return -1; } } } } ``` ##2. 布局 ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <SurfaceView android:id="@+id/surfaceview" android:layout_width="match_parent" android:layout_height="match_parent" /> <Button android:id="@+id/btnStartStop" android:layout_width="60dp" android:layout_height="40dip" android:layout_centerHorizontal="true" android:layout_alignParentBottom="true" android:text="开始" /> </RelativeLayout> ``` ##3. 权限 ``` <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> ``` 求大神解答
Android打砖块代码 其中系统说格式错误 求帮助
我这边有一个打砖块代码,我将它移植到我的按钮事件触发里 提示我格式错误 下面前两个是打砖块代码 ,后两个是转到我的里面之后的, 标注了,请帮忙。 package ab.cc; import android.app.Activity; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.Window; import android.view.WindowManager; public class BaomingActivity extends Activity { BallView myView; static int screenWidth; static int screenHeight; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* 定义DisplayMetrics对象 */ DisplayMetrics dm = new DisplayMetrics(); /* 取得窗口属性 */ getWindowManager().getDefaultDisplay().getMetrics(dm); /* 窗口的宽度 */ screenWidth = dm.widthPixels; /* 窗口的高度 */ screenHeight = dm.heightPixels; // setTitle("宽"+screenWidth+" 高"+screenHeight); /* 设置为无标题栏 */ requestWindowFeature(Window.FEATURE_NO_TITLE); /* 设置为全屏模式 */ getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); myView = new BallView(this); //设置显示GameSurfaceView视图 setContentView(myView); }//end of onCreate() //触笔事件 public boolean onTouchEvent(MotionEvent event) { return true; } //按键按下事件 public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { //菜单按键-设为初始菜单 case KeyEvent.KEYCODE_MENU: myView.resetGame(); //重新开始 break; //中间按键 case KeyEvent.KEYCODE_DPAD_CENTER: myView.ball_isRun = !myView.ball_isRun;//开始//暂停 break; //左方向键 case KeyEvent.KEYCODE_DPAD_LEFT: if(myView.ball_isRun){ if(myView.board_left<=myView.board_x_move) { myView.board_left=0; myView.board_right=myView.board_length; }else{ myView.board_left-=myView.board_x_move; myView.board_right-=myView.board_x_move;} } break; //右方向键 case KeyEvent.KEYCODE_DPAD_RIGHT: if(myView.ball_isRun){ if(screenWidth-myView.board_right<=myView.board_x_move ) { myView.board_left=screenWidth-myView.board_length; myView.board_right=screenWidth; }else{ myView.board_left+=myView.board_x_move; myView.board_right+=myView.board_x_move; } } break; //上方向键 case KeyEvent.KEYCODE_DPAD_UP: if(myView.ball_isRun){ if( myView.board_alterable_top==myView.board_default_top) { myView.board_alterable_top-=myView.boardYadd; myView.board_alterable_bottom-=myView.boardYadd; } } break; //下方向键 case KeyEvent.KEYCODE_DPAD_DOWN: if(myView.ball_isRun){ if( myView.board_alterable_top==myView.board_default_top-myView.boardYadd ) { myView.board_alterable_top=myView.board_default_top; myView.board_alterable_bottom=myView.board_alterable_top+myView.board_thickness; } } break; //返回键 case KeyEvent.KEYCODE_BACK: this.finish(); break; }//end switch return false; } //按键弹起事件 public boolean onKeyUp(int keyCode, KeyEvent event) { return true; } public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { return true; } } package ab.cc; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RadialGradient; import android.graphics.Shader; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; public class BallView extends SurfaceView implements SurfaceHolder.Callback, Runnable { //线程延时控制 final int ball_sleep=1;//毫秒,延时越大,球速越慢 final int ball_r= 8;//小球半径 final float ball2_r= 8;//底下滚珠小球半径 final int ballXorYadd = 4;//小球的基本位移。测试可行值:2,4 //获取屏幕宽度和高度 int screen_width;//320; int screen_height;//480; //砖的属性 int brick_width;//每块砖宽 int brick_height;//每块砖高 boolean brick_exist[];//砖是否存在 int k ;// 列//到for循环里才初始化 int j ;// 行 int brick_left = brick_width*(k-1);//到判断语句才初始化 int brick_right = brick_width*k; int brick_top = brick_height*j; int brick_bottom = brick_height*(j+1); //挡板的属性 int board_length;//挡板长度:80比较合适,可以随意修改,但别超过screen_width final int boardYadd = 16;//按上下键时挡板y方向位移量。经验证4、8、16可以,12不行 final int board_x_move = 30;//挡板x方向位移量:可以随意自定义 int board_left;//挡板左侧(可变) int board_right;//挡板右侧(可变) int board_thickness;//挡板厚度 int board_default_top;//即435,挡板的top面初始位置 int board_alterable_top;//挡板上侧(可变) int board_alterable_bottom;//挡板下侧(可变) int ball_default_x;//球的初始x坐标 int ball_default_y;//球的初始y坐标 //球的即时坐标(可变): int ball_x;//球心横坐标 int ball_y;//球心纵坐标 //球的前一步的y坐标 int ball_previous_y; int ball_x_speed;//球的横向偏移量//可变 int ball_y_speed;//球的纵向偏移量//可变 boolean ball_isRun;//球是否在动 // 控制循环 boolean mbLoop; // 定义SurfaceHolder对象 SurfaceHolder mSurfaceHolder = null; //获得分数 int score; /* 唤醒渐变渲染 */ Shader mRadialGradient = null; //------------------------------------------------------------------------------------------------------// public BallView(Context context) { super(context); // 实例化SurfaceHolder mSurfaceHolder = this.getHolder(); // 添加回调 mSurfaceHolder.addCallback(this); this.setFocusable(true); //获取屏幕宽度和高度 screen_width = BaomingActivity.screenWidth;//320 screen_height = BaomingActivity.screenHeight;//480 //砖的属性 brick_width = screen_width/5;//每块砖宽64 brick_height = screen_height/15;//每块砖高32 //挡板的属性 board_length = screen_width/4;//挡板长度:80比较合适,可以随意修改,但别超过screen_width board_left = (screen_width-board_length)/2;//挡板左侧(可变) board_right = (screen_width+board_length)/2;//挡板右侧(可变) board_thickness = 5;//挡板厚度 board_default_top = 13*screen_height/15;//即435,挡板的top面初始位置 board_alterable_top = board_default_top;//挡板上侧(可变) board_alterable_bottom = board_alterable_top+board_thickness;//挡板下侧(可变) ball_default_x = screen_width/2;//球的初始x坐标 ball_default_y = board_default_top - ball_r;//球的初始y坐标 //球的即时坐标(可变): ball_x = ball_default_x; ball_y = ball_default_y; //球的前一步的y坐标 ball_previous_y = 0; ball_x_speed = ballXorYadd;//球的横向偏移量 ball_y_speed = ballXorYadd;//球的纵向偏移量 mbLoop = true; ball_isRun = false; score=0; brick_exist = new boolean[25]; for (int i = 0; i < 25; i++) { brick_exist[i] = true; } /* 构建RadialGradient对象,设置半径的属性 */ mRadialGradient = new RadialGradient(ball_x, ball_y, ball_r,//球中心坐标x,y,半径r new int[]{Color.WHITE,Color.BLUE,Color.GREEN,Color.RED,Color.YELLOW},//颜色数组 null,//颜色数组中每一种颜色对应的相对位置,为空的话就是平均分布,由中心向外排布 Shader.TileMode.REPEAT);//渲染模式:重复 } public void resetGame(){ ball_isRun = false; score =0;//分数 ball_x_speed = ballXorYadd;//球的横向偏移量 ball_y_speed = ballXorYadd;//球的纵向偏移量 ball_x = screen_width/2;//球心起始横坐标 ball_y = board_default_top - ball_r;//球心起始纵坐标 board_left = (screen_width-board_length)/2;//挡板左侧 board_right = (screen_width+board_length)/2;//挡板右侧 board_alterable_top = board_default_top;//挡板上侧 board_alterable_bottom = board_alterable_top+board_thickness;//挡板下侧 for (int i = 0; i < 25; i++) { brick_exist[i] = true; } } //---------------------------------绘图循环开始---------------------------------- public void run() { while (mbLoop&&!Thread.currentThread().isInterrupted()) { try { Thread.sleep(ball_sleep); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } //球的前一步y坐标 ball_previous_y = ball_y; if (ball_isRun) { ballRunning();// 让小球移动 boardPositionCheck();//检测挡板是否处于“中线”位置,是就随小球上升一步,直至到“上线” hitWallCheck();//墙壁碰撞检测 hitBoardCheck();//挡板碰撞检测 hitBrickCheck();//砖块碰撞检测 } synchronized (mSurfaceHolder) { Draw(); } } } //---------------------------------绘图循环结束---------------------------------- //------------------------------------------------------------------------------ //让小球移动 public void ballRunning() { ball_x += ball_x_speed; ball_y -= ball_y_speed; } //朝左或朝右碰撞后小球水平方向逆向 public void ballLeftOrRightHit() { ball_x_speed *= -1; } //朝上或朝下碰撞后小球竖直方向逆向 public void ballUpOrDownHit() { ball_y_speed *= -1; } public void ballcornerHit() { ball_x_speed *= -1; ball_y_speed *= -1; } public void ballStraightUp() {//功能没实现,这是多余代码 ball_x_speed = 0;//注意在其他地方恢复 ball_y_speed *= -1; } //-------------------墙壁碰撞检测开始------------------------------------- public void hitWallCheck() { // 左碰墙 if (ball_x <= ball_r && ball_y >= ball_r && ball_y <= screen_height) { ballLeftOrRightHit(); // 右碰墙 } if (ball_x >= screen_width - ball_r && //不能写为 else if,因为可能恰好碰到角落。 ball_y >= ball_r && ball_y <= screen_height) { ballLeftOrRightHit(); } // 上碰墙 if (ball_x >= ball_r && ball_x <= screen_width - ball_r && ball_y <= ball_r + brick_height) //、、、、、、、、、、、、、、、25号修改 { ballUpOrDownHit(); } // 下碰墙 if (ball_x >= ball_r && ball_x <= screen_width - ball_r && ball_y >= screen_height-ball_r) { ballUpOrDownHit(); if(score<=10){ score = 0; } else score-=10; } } //-------------------墙壁碰撞检测结束------------------------------------- //-----------------------------挡板碰撞检测开始--------------------------- public void hitBoardCheck() { // 下碰挡板正面 if (ball_x >= ball_r && ball_x <= screen_width - ball_r && //在屏幕内,起码条件 ball_x >= board_left && ball_x <= board_right && //在挡板X域上方 ball_y == board_alterable_top - ball_r &&//球面与挡板相切 ball_previous_y <= board_alterable_top - ball_r //确定球是从上方下落 ) { if(board_alterable_top==board_default_top-boardYadd ){//如果弹簧伸张,挡板位于上线 ballHitBoardlower();//作用:ball_y_move减小;挡板被打下;小球Y向运动反向 } else if(board_alterable_top==board_default_top){//如果弹簧压缩,挡板位于下线 boardHitBallHigher();//作用:ball_y_move增加;挡板弹上;小球Y向运动反向 } } //斜碰挡板右上角//经验证有效 else if(Math.pow(board_right-ball_x, 2)+Math.pow(board_alterable_top-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x>board_right && ball_y<board_alterable_top) { ballcornerHit(); } //斜碰挡板的左上角//经验证有效 else if(Math.pow(board_left-ball_x, 2)+Math.pow(board_alterable_top-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x<board_left && ball_y<board_alterable_top) { ballcornerHit(); } } //-----------------------------挡板碰撞检测结束-------------------------- private void boardHitBallHigher() {//增强 ballUpOrDownHit();//小球Y方向反向,ball_y_speed变为正数 if(ball_y_speed == ballXorYadd ){ ball_y_speed += ballXorYadd;//离开挡板后小球Y方向速度增强 } if( boardYadd > ball_y_speed ){//在线程这一轮,小球上升多少,挡板就上升多少。 board_alterable_top = board_default_top - ball_y_speed; board_alterable_bottom= board_alterable_top+board_thickness;//挡板下层面 } } //检测挡板是否处于“中线”位置,是就随小球上升一步,直至到“上线” private void boardPositionCheck() {//还可直接利用球的位置刷新,board_top与球心相差ball_r if(board_alterable_top < board_default_top && board_alterable_top > board_default_top-boardYadd){ //挡板随球上升 if(board_alterable_top - ball_y_speed >= board_default_top-boardYadd){ board_alterable_top -= ball_y_speed;//挡板上层面 board_alterable_bottom= board_alterable_top+board_thickness;//挡板下层面 } else{ board_alterable_top = board_default_top-boardYadd;//挡板上层面 board_alterable_bottom= board_alterable_top+board_thickness;//挡板下层面 } } } private void ballHitBoardlower() {//减弱 board_alterable_top=board_default_top; board_alterable_bottom=board_default_top+board_thickness;//挡板被打退 ballUpOrDownHit();//小球Y方向反向 if(ball_y_speed==2*ballXorYadd){ ball_y_speed -= ballXorYadd;//小球Y方向速度减弱 } } //砖块碰撞检测开始----------------------------------------------------------- public void hitBrickCheck() { for (int i = 0; i <25 ; i++) { if (brick_exist[i]) { k = i % 5+1;// 1,2,3,4,5循环 j = i / 5+1;// 1,1,1,1,1;2,2,2,2,2,;...;5,5,5,5,5 brick_left = brick_width*(k-1); brick_right = brick_width*k; brick_top = brick_height*j; brick_bottom = brick_height*(j+1); //朝下碰砖的top面 AAAAAAAAAAAAAAAAAAAAA if(ball_x >= brick_left && ball_x <= brick_right && ball_y >= brick_top-ball_r && ball_y < brick_top) { ballUpOrDownHit(); brick_exist[i] = false; score+=4; //朝下正碰2砖中间,i砖右上角检测 if(k!=5 && ball_x == brick_right)//如果不是第5列砖的右侧边 { //如果砖[i+1]存在 if(brick_exist[i+1]){ brick_exist[i+1] = false; score+=4; } } //朝下正碰2砖中间,i砖左上角检测 else if(k!=1 && ball_x == brick_left)//如果不是第1列砖的左侧边 { //如果砖[i-1]存在 if(brick_exist[i-1]){ brick_exist[i-1] = false; score+=4; } } } //朝上碰砖的bottom面 BBBBBBBBBBBBBBBBB else if(ball_x >= brick_left && ball_x <= brick_right && ball_y > brick_bottom&& ball_y <= brick_bottom + ball_r ) { ballUpOrDownHit(); brick_exist[i] = false; score+=4; //朝上正碰2块砖中间--i砖的右下角检测 if(k!=5 && ball_x == brick_right) //如果不是第5列砖的右侧边 { if(brick_exist[i+1]){//如果砖[i+1]存在 brick_exist[i+1] = false; score+=4; } } //朝上正碰2块砖中间--i砖的左下角检测 else if(k!=1 && ball_x == brick_left) //如果不是第1列砖的左侧边 { if(brick_exist[i-1]){//如果砖[i-1]存在 brick_exist[i-1] = false; score+=4; } } } //朝右碰砖的left面CCCCCCCCCCCCCCCCC else if(ball_x >= brick_left -ball_r&&ball_x < brick_left&& ball_y >= brick_top && ball_y <= brick_bottom) { ballLeftOrRightHit(); brick_exist[i] = false; score+=4; //朝右正碰2块砖中间,左下角检测 if(j!=5 && ball_y == brick_bottom)//如果不是第5行砖的下侧边 { if(brick_exist[i+5]){//如果砖[i+5]存在 brick_exist[i+5] = false; score+=4; } } //朝右正碰2块砖中间,左上角检测 else if(j!=1 && ball_y == brick_top)//如果不是第1行砖的上侧边 { if(brick_exist[i-5]){//如果砖[i-5]存在 brick_exist[i-5] = false; score+=4; } } } //朝左碰砖的right面DDDDDDDDDDDDDDDDDD else if(ball_x >= brick_right && ball_x <= brick_right+ball_r&& ball_y >= brick_top && ball_y <= brick_bottom) { ballLeftOrRightHit(); brick_exist[i] = false; score+=4; //朝左正碰2块砖中间,右下角检测 if(j!=5 && ball_y == brick_bottom )//如果不是第5行砖的下侧边 { if(brick_exist[i+5]){//如果砖[i+5]存在 brick_exist[i+5] = false; score+=4; } } //朝左正碰2块砖中间,右上角检测 else if(j!=1 && ball_y == brick_top )//如果不是第1行砖上侧边 { if(brick_exist[i-5]){//如果砖[i-5]存在 brick_exist[i-5] = false; score+=4; } } } ///////////////////////////////////////// //斜碰i砖的左下角EEEEEEEEEEEEEEEEEEEEEEEE else if(( i-1<0||(i-1>=0&&!brick_exist[i-1]) ) && (i+5>=25||(i+5<25&&!brick_exist[i+5]) )&& Math.pow(brick_left-ball_x, 2)+Math.pow(brick_bottom-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x>brick_left-ball_r && ball_x<brick_left && ball_y>brick_bottom && ball_y<brick_bottom+ball_r ) { ballcornerHit(); brick_exist[i] = false; score+=4; } //斜碰i砖的右下角FFFFFFFFFFFFFFFFFFFFFFFFFF else if( (i+1>=25||(i+1<25&&!brick_exist[i+1]) )&& (i+5>=25||(i+5<25&&!brick_exist[i+5]) )&& Math.pow(brick_right-ball_x, 2)+Math.pow(brick_bottom-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x>brick_right&&ball_x<brick_right+ball_r&& ball_y>brick_bottom&&ball_y<brick_bottom+ball_r ) { Log.v("----------", "right bottom hit"+i+":"+brick_exist[i]); ballcornerHit(); brick_exist[i] = false; score+=4; } //斜碰i砖的右上角GGGGGGGGGGGGGGGGGGGGGGGG else if( (i+1>=25||(i+1<25&&!brick_exist[i+1]) )&& (i-5<0||(i-5>0&&!brick_exist[i-5]) )&& Math.pow(brick_right-ball_x, 2)+Math.pow(brick_top-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x>brick_right && ball_x<brick_right+ball_r&& ball_y>brick_top-ball_r && ball_y<brick_top) { ballcornerHit(); brick_exist[i] = false; score+=4; } //斜碰i砖的左上角HHHHHHHHHHHHHHHHHHHHHHHHHH else if((i-1<0||(i-1>=0&&!brick_exist[i-1])) && (i-5<0||(i-5>=0&&!brick_exist[i-5])) && Math.pow(brick_left-ball_x, 2)+Math.pow(brick_top-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x>brick_left-ball_x && ball_x<brick_left && ball_y>brick_top-ball_r && ball_y<brick_top ) { ballcornerHit(); brick_exist[i] = false; score+=4; } }//end if }//end for }//end hitBrickCheck() //砖块碰撞检测结束----------------------------------------------------------- //------------------------------------------ public boolean gameOver(){ int count = 0; for(boolean s:brick_exist){ if(!s){ count++; } } if(count == 25){ return true; }else{ return false; } } //------------------------------------------ //---------------绘图方法开始------------------------ public void Draw() { // 锁定画布,得到canvas Canvas canvas = mSurfaceHolder.lockCanvas(); if (mSurfaceHolder == null || canvas == null) { return; } // 绘图 Paint mPaint = new Paint(); // 设置取消锯齿效果 mPaint.setAntiAlias(true); mPaint.setColor(Color.BLACK); // 绘制矩形--背景 canvas.drawRect(0, 0, screen_width, brick_height-2, mPaint); mPaint.setColor(Color.GREEN); // 绘制矩形--背景 canvas.drawRect(0, brick_height-2, screen_width, screen_height, mPaint); mPaint.setColor(Color.RED);//设置字体颜色 mPaint.setTextSize(brick_height-7);//设置字体大小 canvas.drawText("得分:"+score, 0, brick_height-7, mPaint); // 绘制顶层挡板````````````````````````````````````````````````````````25号修改 mPaint.setColor(Color.BLACK);//设置颜色 mPaint.setStrokeWidth(4);//设置粗细 canvas.drawLine(0, brick_height-2, screen_width, brick_height-2, mPaint); for (int i = 0; i <25 ; i++) { if (brick_exist[i]) { k = i % 5+1;// 1,2,3,4,5循环 j = i / 5+1;// 1,1,1,1,1;2,2,2,2,2,;...;5,5,5,5,5 brick_left = brick_width*(k-1); brick_right = brick_width*k; brick_top = brick_height*j; brick_bottom = brick_height*(j+1); mPaint.setStyle(Paint.Style.FILL);// 设置实心画笔 mPaint.setColor(Color.YELLOW); canvas.drawRect(brick_left+1, brick_top+1, brick_right-1,brick_bottom-1, mPaint); mPaint.setStyle(Paint.Style.STROKE);// 设置空心画笔 mPaint.setStrokeWidth(2);//设置粗细 mPaint.setColor(Color.BLUE); canvas.drawRect(brick_left+3, brick_top+3, brick_right-3,brick_bottom-3, mPaint); } } // 设置实心画笔 mPaint.setStyle(Paint.Style.FILL); { mPaint.setShader(mRadialGradient); canvas.drawCircle(ball_x, ball_y, ball_r, mPaint); } Paint mPaint2 = new Paint(); // 设置取消锯齿效果 mPaint2.setAntiAlias(true); // 设置实心画笔 mPaint2.setStyle(Paint.Style.FILL); { mPaint2.setColor(Color.BLACK); /* 绘制矩形挡板 */ canvas.drawRect(board_left, board_alterable_top, board_right, board_alterable_bottom,mPaint2); float board2_bottom = screen_height - 2*ball2_r;//164 float board2_top = board2_bottom - 4;//160 //线段端点坐标数组 float x0 = board_left+(board_right-board_left)/4; float y0 = board_alterable_bottom;//440或者444 float springAdd = (board2_top- board_alterable_bottom)/8;//即2.5或者2:弹簧小线段的y向长度 float springWidth = 5.0f;//弹簧小线段的x向长度 float x1 = x0 - springWidth; float y1 = y0 + springAdd; float x2 = x0 + springWidth; float y2 = y0 + 3*springAdd; float x3 = x1 ; float y3 = y0 + 5*springAdd; float x4 = x2; float y4 = y0 + 7*springAdd; float x5 = x0 ; float y5 = board2_top;//即460 float between_spring = (board_right-board_left)/2; float pts[] = { x0,y0,x1,y1, x1,y1,x2,y2, x2,y2,x3,y3, x3,y3,x4,y4, x4,y4,x5,y5}; float pts2[] = {x0+between_spring,y0, x1+between_spring,y1, x1+between_spring,y1, x2+between_spring,y2, x2+between_spring,y2, x3+between_spring,y3, x3+between_spring,y3, x4+between_spring,y4, x4+between_spring,y4, x5+between_spring,y5}; mPaint2.setStrokeWidth(2);//设置弹簧粗细 //绘制2个弹簧 canvas.drawLines(pts, mPaint2); canvas.drawLines(pts2, mPaint2); //绘制下层挡板 canvas.drawRect(board_left, board2_top, board_right, board2_bottom,mPaint2); mPaint2.setColor(Color.BLACK);// // 绘制最下面的两个“轮子”(圆心x,圆心y,半径r,p) canvas.drawCircle(board_left+ball2_r, screen_height-ball2_r, ball2_r, mPaint2);//圆 canvas.drawCircle(board_right-ball2_r, screen_height-ball2_r, ball2_r, mPaint2); mPaint2.setColor(Color.WHITE);// canvas.drawPoint(board_left+ball2_r, screen_height-ball2_r, mPaint2);//绘制左轮轮心 canvas.drawPoint(board_right-ball2_r, screen_height-ball2_r, mPaint2);//绘制右轮轮心 }//实心画笔mPaint2结束 if(gameOver()){ // mbLoop = false;//注释掉的话GAME OVER后也可重启 ball_isRun = false; mPaint2.setColor(Color.BLACK);//设置字体颜色 mPaint2.setTextSize(40.0f);//设置字体大小 canvas.drawText("GAME OVER", screen_width/32+40, screen_height/16*9-70, mPaint2); mPaint2.setTextSize(20.0f);//设置字体大小 canvas.drawText("Press \"MENU\" button to restart,", screen_width/32, //320/32=10 screen_height/16*9, //480/16=30,30*9=270 mPaint2); canvas.drawText("Press \"BACK\" button to exit.", screen_width/32, //320/32=10 screen_height/16*10, //480/16=30,30*10=300 mPaint2); } // 绘制后解锁,绘制后必须解锁才能显示 mSurfaceHolder.unlockCanvasAndPost(canvas); }// end of Draw() //---------------------绘图方法结束----------------------------------------------- // 在surface的大小发生改变时激发 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } // 在surface创建时激发 public void surfaceCreated(SurfaceHolder holder) { new Thread(this).start();// 开启绘图线程 } // 在surface销毁时激发 public void surfaceDestroyed(SurfaceHolder holder) { // 停止循环 mbLoop = false; } } package sen.tan; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; public class dazhuankuaiActivity extends Activity { BallView myview; public static int screenWidth ; public static int screenHeight; private TextView textview; Button kaishi,jieshu,guanyu; ImageView image; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); String string = "欢迎进入疯狂打砖块游戏"; image = (ImageView) this.findViewById(R.id.image); image.setImageResource(R.drawable.img1); textview =(TextView) this.findViewById(R.id.textview); textview.setTextSize(20); textview.setTextColor(Color.GREEN); textview.setBackgroundColor(Color.RED); textview.setText(string); kaishi=(Button)findViewById(R.id.button1); guanyu=(Button)findViewById(R.id.button2); jieshu=(Button)findViewById(R.id.button3); kaishi.setWidth(250); guanyu.setWidth(200); jieshu.setWidth(150); kaishi.setTextSize(35); guanyu.setTextSize(29); jieshu.setTextSize(24); jieshu.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v) { dazhuankuaiActivity.this.finish(); } }); guanyu.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v){ textview.setText("本游戏由邵明森和谭明星制作,此游戏控制左右按键,来回移动挡板,不让小球掉落,当小球把上方砖块全部打完时,游戏胜利"); } }); kaishi.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v){ public void onCreate(Bundle savedInstanceState)这里显示的错误 显示的是上面两个括号标示不对。 { super.onCreate(savedInstanceState); DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); screenWidth = dm.widthPixels; screenHeight = dm.heightPixels; setTitle("宽"+screenWidth+" 高"+screenHeight); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); myview = new BallView(this); setContentView(myview); } } public boolean onTouchEvent(MotionEvent event) { return true; } public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_MENU: myview.resetGame(); break; case KeyEvent.KEYCODE_DPAD_CENTER: myview.ball_isRun = !myview.ball_isRun; break; case KeyEvent.KEYCODE_DPAD_LEFT: if(myview.ball_isRun){ if(myview.board_left<=myview.board_x_move) { myview.board_left=0; myview.board_right=myview.board_length; }else{ myview.board_left-=myview.board_x_move; myview.board_right-=myview.board_x_move;} } break; case KeyEvent.KEYCODE_DPAD_RIGHT: if(myview.ball_isRun){ if(screenWidth-myview.board_right<=myview.board_x_move ) { myview.board_left=screenWidth-myview.board_length; myview.board_right=screenWidth; }else{ myview.board_left+=myview.board_x_move; myview.board_right+=myview.board_x_move; } } break; case KeyEvent.KEYCODE_DPAD_UP: if(myview.ball_isRun){ if( myview.board_alterable_top==myview.board_default_top) { myview.board_alterable_top-=myview.boardYadd; myview.board_alterable_bottom-=myview.boardYadd; } } break; case KeyEvent.KEYCODE_DPAD_DOWN: if(myview.ball_isRun){ if( myview.board_alterable_top==myview.board_default_top-myview.boardYadd ) { myview.board_alterable_top=myview.board_default_top; myview.board_alterable_bottom=myview.board_alterable_top+myview.board_thickness; } } break; case KeyEvent.KEYCODE_BACK: this.finish(); break; } return false; } public boolean onKeyUp(int keyCode, KeyEvent event) { return true; } public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { return true; } } ); } }
Android中关于背景图片的问题,求助。
主程序中有俩个.java文件,分别如下。在layout中设置了android:background="@drawable/cc",然而被没有出现背景图片,还是黑兮兮的一片。求大牛帮助,不甚感激。 代码如下: **MainActivity.java** package com.example.homework; import android.app.Activity; import android.os.Bundle; import android.view.Window; import android.view.WindowManager; public class MainActivity extends Activity { public static MainActivity instance; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); instance = this; //设置全屏 this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); requestWindowFeature(Window.FEATURE_NO_TITLE); //显示自定义的SurfaceView视图 setContentView(new MySurfaceView(this)); } } **MySurfaceView.java文件** package com.example.homework; import android.app.Service; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.SurfaceHolder.Callback; public class MySurfaceView extends SurfaceView implements Callback, Runnable { private SurfaceHolder sfh; private Paint paint; private Thread th; private boolean flag; private Canvas canvas; private int screenW, screenH; //声明一个传感器管理器 private SensorManager sm; //声明一个传感器 private Sensor sensor; //声明一个传感器监听器 private SensorEventListener mySensorListener; //圆形的X,Y坐标 private int arc_x, arc_y; //传感器的xyz值 private float x = 0, y = 0, z = 0; /** * SurfaceView初始化函数 */ public MySurfaceView(Context context) { super(context); sfh = this.getHolder(); sfh.addCallback(this); paint = new Paint(); paint.setColor(Color.WHITE); paint.setAntiAlias(true); setFocusable(true); //获取传感器管理类实例 sm = (SensorManager) MainActivity.instance.getSystemService(Service.SENSOR_SERVICE); //实例一个重力传感器实例 sensor = sm.getDefaultSensor(Sensor.TYPE_GRAVITY); //实例传感器监听器 mySensorListener = new SensorEventListener() { @Override //传感器获取值发生改变时在响应此函数 public void onSensorChanged(SensorEvent event) { x = event.values[0]; //x>0 说明当前手机左翻 x<0右翻 y = event.values[1]; //y>0 说明当前手机下翻 y<0上翻 z = event.values[2]; //z>0 手机屏幕朝上 z<0 手机屏幕朝下 arc_x -= x; arc_y += y; } @Override //传感器的精度发生改变时响应此函数 public void onAccuracyChanged(Sensor sensor, int accuracy) { } }; //为传感器注册监听器 sm.registerListener(mySensorListener, sensor, SensorManager.SENSOR_DELAY_NORMAL); } /** * SurfaceView视图创建,响应此函数 */ @Override public void surfaceCreated(SurfaceHolder holder) { screenW = this.getWidth(); screenH = this.getHeight(); flag = true; //实例线程 th = new Thread(this); //启动线程 th.start(); } /** * 游戏绘图 */ public void myDraw() { try { canvas = sfh.lockCanvas(); if (canvas != null) { canvas.drawColor(Color.BLACK); paint.setColor(Color.RED); canvas.drawArc(new RectF(arc_x, arc_y, arc_x + 50, arc_y + 50), 0, 360, true, paint); paint.setColor(Color.YELLOW); canvas.drawText("当前重力传感器的值:", arc_x - 50, arc_y - 30, paint); canvas.drawText("x=" + x+" "+ "y=" + y +" "+ "z=" + z, arc_x - 50, arc_y, paint); String temp_str = "温馨提示: "; String temp_str2 = ""; String temp_str3 = ""; if (x < 1 && x > -1 && y < 1 && y > -1) { temp_str2 += "当前手机处于水平放置的状态"; if (z > 0) { temp_str3 += "并且屏幕朝上"+" "+"X轴的测试值:" + x + " " + "Y轴的测试值:" + y + " " + "Z轴的测试值:" + z; } else { temp_str3 += "并且屏幕朝下,提示别躺着玩手机,对眼睛不好哟~"+" "+"X轴的测试值:" + x + " " + "Y轴的测试值:" + y + " " + "Z轴的测试值:" + z; } } else { if (x > 1) { temp_str2 += "当前手机处于向左翻的状态"+" "; } else if (x < -1) { temp_str2 += "当前手机处于向右翻的状态"+" "; } if (y > 1) { temp_str2 += "当前手机处于向下翻的状态"+" "; } else if (y < -1) { temp_str2 += "当前手机处于向上翻的状态"+" "; } if (z > 0) { temp_str3 += "并且屏幕朝上"+" "+"X轴的测试值:" + x + " " + "Y轴的测试值:" + y + " " + "Z轴的测试值:" + z; } else { temp_str3 += "并且屏幕朝下,提示别躺着玩手机,对眼睛不好哟~"+" "+"X轴的测试值:" + x + " " + "Y轴的测试值:" + y + " " + "Z轴的测试值:" + z; } } paint.setTextSize(10); canvas.drawText(temp_str, 0, 50, paint); canvas.drawText(temp_str2, 0, 80, paint); canvas.drawText(temp_str3, 0, 110, paint); } } catch (Exception e) { // TODO: handle exception } finally { if (canvas != null) sfh.unlockCanvasAndPost(canvas); } } /** * 触屏事件监听 */ @Override public boolean onTouchEvent(MotionEvent event) { return true; } /** * 按键事件监听 */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { return super.onKeyDown(keyCode, event); } /** * 游戏逻辑 */ private void logic() { } @Override public void run() { while (flag) { long start = System.currentTimeMillis(); myDraw(); logic(); long end = System.currentTimeMillis(); try { if (end - start < 50) { Thread.sleep(50 - (end - start)); } } catch (InterruptedException e) { e.printStackTrace(); } } } /** * SurfaceView视图状态发生改变,响应此函数 */ @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } /** * SurfaceView视图消亡时,响应此函数 */ @Override public void surfaceDestroyed(SurfaceHolder holder) { flag = false; } } 以下是布局文件代码 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/cc" > </LinearLayout>
使用MediaRecorder录制视频 录完后没有生成文件
代码如下:package com.example.meadiarecorder3; import java.io.File; import java.io.IOException; import android.app.Activity; import android.content.pm.ActivityInfo; import android.graphics.PixelFormat; import android.hardware.Camera; import android.media.MediaRecorder; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity implements SurfaceHolder.Callback{ private SurfaceView mSurfaceView; private SurfaceHolder mSurfaceHolder; private TextView tvTime; private TextView tvSize; private Button btnStart; private Button btnStop; private Button btnCancel; private MediaRecorder recorder; private Handler handler; private Camera camera; private boolean recording; // 记录是否正在录像,fasle为未录像, true 为正在录像 private int minute = 0; private int second = 0; private String time = ""; private String size = ""; private String name; private File viodFile; private Runnable timeRun = new Runnable() { @Override public void run() { long fileLength = viodFile.length(); if (fileLength < 1024 && fileLength > 0) { size = String.format("%dB/10M", fileLength); } else if (fileLength >= 1024 && fileLength < (1024 * 1024)) { fileLength = fileLength / 1024; size = String.format("%dK/10M", fileLength); } else if (fileLength > (1024 * 1024 * 1024)) { fileLength = (fileLength / 1024) / 1024; size = String.format("%dM/10M", fileLength); } second++; if (second == 60) { minute++; second = 0; } time = String.format("%02d:%02d", minute, second); tvSize.setText(viodFile.getAbsolutePath()); tvTime.setText(time); handler.postDelayed(timeRun, 1000); } }; private Button start;// 开始录制按钮 private Button stop;// 停止录制按钮 private MediaRecorder mediarecorder;// 录制视频的类 private SurfaceView surfaceview;// 显示视频的控件 // 用来显示视频的一个接口,我靠不用还不行,也就是说用mediarecorder录制视频还得给个界面看 // 想偷偷录视频的同学可以考虑别的办法。。嗯需要实现这个接口的Callback接口 private SurfaceHolder surfaceHolder; private String fileName; private SurfaceHolder holder; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏 // 设置横屏显示 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT); // 选择支持半透明模式,在有surfaceview的activity中使用。 getWindow().setFormat(PixelFormat.TRANSLUCENT); setContentView(R.layout.activity_main); fileName = Environment.getExternalStorageDirectory().getAbsolutePath(); name = "video_" + System.currentTimeMillis() + ".mp4"; fileName += File.separator + File.separator + "Ruanko_Jobseeker" + File.separator + name; name = "video_" + System.currentTimeMillis() + ".mp4"; tvSize = (TextView) findViewById(R.id.tv_video_size); tvTime = (TextView) findViewById(R.id.tv_video_time); handler= new Handler(); init(); } private void init() { start = (Button) this.findViewById(R.id.start); stop = (Button) this.findViewById(R.id.stop); start.setOnClickListener(new TestVideoListener()); stop.setOnClickListener(new TestVideoListener()); surfaceview = (SurfaceView) this.findViewById(R.id.surfaceview); holder = surfaceview.getHolder(); holder.addCallback(this); // holder加入回调接口 // setType必须设置,要不出错. holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } class TestVideoListener implements OnClickListener { private static final String TAG = "MainActivity"; @Override public void onClick(View v) { if (v == start) { try { viodFile = new File(Environment.getExternalStorageDirectory().getCanonicalFile() + "/myvideo.mp4"); if (!Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { Toast.makeText(getApplicationContext(), "SD卡不存在,请插卡", 0).show(); return; }else{ if(!viodFile.exists()){ viodFile.getParentFile().mkdirs(); viodFile.createNewFile(); } } mediarecorder = new MediaRecorder();// 创建mediarecorder对象 // 设置录制视频源为Camera(相机) mediarecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); // 设置从麦克风采集声音 mediarecorder.setAudioSource(MediaRecorder.AudioSource.MIC); // 设置录制完成后视频的封装格式THREE_GPP为3gp.MPEG_4为mp4 mediarecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); // 设置录制的视频编码h263 h264 mediarecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264); mediarecorder.setAudioEncoder(MediaRecorder.VideoEncoder.DEFAULT); // 设置视频录制的分辨率。必须放在设置编码和格式的后面,否则报错 mediarecorder.setVideoSize(176, 144); // 设置录制的视频帧率。必须放在设置编码和格式的后面,否则报错 mediarecorder.setVideoFrameRate(20); mediarecorder.setPreviewDisplay(holder.getSurface()); // 设置视频文件输出的路径 mediarecorder.setOutputFile(viodFile.getAbsolutePath()); System.out.println("viodFile.getAbsolutePath()的值为:"+viodFile.getAbsolutePath()); // 准备录制 mediarecorder.prepare(); // 开始录制 mediarecorder.start(); handler.post(timeRun); } catch (IOException e2) { e2.printStackTrace(); } } if (v == stop) { Log.i(TAG, viodFile.toString()); if (mediarecorder != null) { handler.removeCallbacks(timeRun); // 停止录制 mediarecorder.stop(); // 释放资源 mediarecorder.release(); mediarecorder = null; } } } } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // 将holder,这个holder为开始在oncreat里面取得的holder,将它赋给surfaceHolder surfaceHolder = holder; } public void surfaceCreated(SurfaceHolder holder) { // 将holder,这个holder为开始在oncreat里面取得的holder,将它赋给surfaceHolder surfaceHolder = holder; } public void surfaceDestroyed(SurfaceHolder holder) { // surfaceDestroyed的时候同时对象设置为null surfaceview = null; holder = null; mediarecorder = null; } } 代码是没问题的 可以运行 可以录制和暂停 设置录制视频地址的代码是 viodFile = new File(Environment.getExternalStorageDirectory().getCanonicalFile() + "/myvideo.mp4"); mediarecorder.setOutputFile(viodFile.getAbsolutePath()); 这两行已经把地址设置好了 按道理来说 录完之后就可以找到文件了 但是没有! 求助各位大神,到底是哪里出了问题,有录制视频的号框架推荐就指点一二,或者有更好的代码就发小弟一份,不胜感激。。
Android问题 贪吃蛇程序报错
![图片说明](https://img-ask.csdn.net/upload/201605/29/1464510848_54035.png) 这里调用就报错: if ((p[0] >= activity.x1 - 80) && (p[0] <= activity.x1 + 80) && (p[1] >= activity.y1 - 16) && (p[1] <=activity.y1 + 16)) { activity.onStop(); return; } // 撞墙 if ((p[0] < 16) || (p[1] < 16) || (p[0] > activity.screenW - 16) || (p[1] > activity.screenH - 16)) { activity.onStop(); // activity.onResume(); return; } 下面是代码: public class GameThread extends Thread { private GameView view; private SurfaceHolder holder; public boolean pauseFlag = false;// 是否暂停 public GameThread(GameView view) { this.view = view; holder = view.getHolder(); } @Override public void run() { Canvas canvas; while (true) { canvas = null; if (!pauseFlag) { try { canvas = holder.lockCanvas(); synchronized (holder) { view.drawGame(canvas); } } finally { if (canvas != null) { holder.unlockCanvasAndPost(canvas); } } } try { Thread.sleep(200); } catch (Exception e) { e.printStackTrace(); } } } } public class MainActivity extends Activity { private GameView gameView; private GestureDetector gestureDetector;// 处理手势 public int fx = 0; // 食物的X坐标 public int fy = 0;// 食物的Y坐标 public int size = 16; // 蛇身的大小 public int changdu = 2;// 蛇身长度 public int direction = 3;// 蛇的移动方向,分别使用 0上,1下,2左,3右 public int x = 16; // 移动的X坐标 public int y = 16; // 移动的Y坐标 public int x1 = 0; // 障碍物X坐标 public int y1 = 0; // Y坐标 public ArrayList<int[]> path = new ArrayList<int[]>();// 记录运行的路径 public HashMap<Integer, Integer> roadBlock = new HashMap<Integer, Integer>();// 障碍物 public int screenW; // 屏幕的宽度 public int screenH; // 屏幕的高度 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 初始化视图 initView(); // 初始化地图 initMap(); // 初始化游戏(手势) initGame(); } private void initGame() { gestureDetector = new BuileGesture(this, new BuileGesture.OnGestureResult() { @Override public void onGestureResult(int direction) { // 获取从手势处理类得到的手势方向 MainActivity.this.direction = direction; Toast.makeText(MainActivity.this, "方向:" + direction, Toast.LENGTH_SHORT).show(); } }).Builde(); } private void initMap() { DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); screenW = metrics.widthPixels; screenH = metrics.heightPixels; // 初始化食物 Random rd = new Random(System.currentTimeMillis()); int tempX = rd.nextInt(screenW / 16); int tempY = rd.nextInt(screenH / 16); // ... fx = tempX * 16; fy = tempY * 16; // 初始化障碍物 x1=screenW/2; y1=screenH/2; } private void initView() { // 去标题栏 requestWindowFeature(Window.FEATURE_NO_TITLE); // 设置全屏 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // 绑定视图 gameView = new GameView(MainActivity.this); setContentView(gameView); } @Override public boolean onTouchEvent(MotionEvent event) { // 将触摸事件和手势处理类绑定到一起 return gestureDetector.onTouchEvent(event); } @Override public void onResume() { super.onResume(); // 游戏继续或重新开始 // ... ... Toast.makeText(MainActivity.this, "游戏开始", Toast.LENGTH_SHORT).show(); gameView.gameThread.pauseFlag = false; } @Override protected void onPause() { super.onPause(); // 游戏暂停 // ... ... gameView.gameThread.pauseFlag = true; } @Override public void onStop() { super.onStop(); // 游戏结束 // ... ... Toast.makeText(MainActivity.this, "游戏结束", Toast.LENGTH_SHORT).show(); gameView.gameThread.pauseFlag = true; return ; } }
重力感应控制画布小球问题
import android.app.Activity; import android.content.Context; import android.content.pm.ActivityInfo; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.Window; import android.view.WindowManager; import android.view.SurfaceHolder.Callback; public class SurfaceViewAcitvity extends Activity { MyView mAnimView = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 全屏显示窗口 requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); //强制横屏 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); // 显示自定义的游戏View mAnimView = new MyView(this); setContentView(mAnimView); } public class MyView extends SurfaceView implements Callback,Runnable ,SensorEventListener{ /**每50帧刷新一次屏幕**/ public static final int TIME_IN_FRAME = 50; /** 游戏画笔 **/ Paint mPaint = null; Paint mTextPaint = null; SurfaceHolder mSurfaceHolder = null; /** 控制游戏更新循环 **/ boolean mRunning = false; /** 游戏画布 **/ Canvas mCanvas = null; /**控制游戏循环**/ boolean mIsRunning = false; /**SensorManager管理器**/ private SensorManager mSensorMgr = null; Sensor mSensor = null; /**手机屏幕宽高**/ int mScreenWidth = 0; int mScreenHeight = 0; /**小球资源文件越界区域**/ private int mScreenBallWidth = 0; private int mScreenBallHeight = 0; /**游戏背景文件**/ private Bitmap mbitmapBg; /**小球资源文件**/ private Bitmap mbitmapBall; /**小球的坐标位置**/ private float mPosX = 200; private float mPosY = 0; /**重力感应X轴 Y轴 Z轴的重力值**/ private float mGX = 0; private float mGY = 0; private float mGZ = 0; public MyView(Context context) { super(context); /** 设置当前View拥有控制焦点 **/ this.setFocusable(true); /** 设置当前View拥有触摸事件 **/ this.setFocusableInTouchMode(true); /** 拿到SurfaceHolder对象 **/ mSurfaceHolder = this.getHolder(); /** 将mSurfaceHolder添加到Callback回调函数中 **/ mSurfaceHolder.addCallback(this); /** 创建画布 **/ mCanvas = new Canvas(); /** 创建曲线画笔 **/ mPaint = new Paint(); mPaint.setColor(Color.WHITE); /**加载小球资源**/ mbitmapBall = BitmapFactory.decodeResource(this.getResources(), R.drawable.ball); /**加载游戏背景**/ mbitmapBg = BitmapFactory.decodeResource(this.getResources(), R.drawable.bg); /**得到SensorManager对象**/ mSensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE); mSensor = mSensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); // 注册listener,第三个参数是检测的精确度 //SENSOR_DELAY_FASTEST 最灵敏 因为太快了没必要使用 //SENSOR_DELAY_GAME 游戏开发中使用 //SENSOR_DELAY_NORMAL 正常速度 //SENSOR_DELAY_UI 最慢的速度 mSensorMgr.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_GAME); } private void Draw() { /**绘制游戏背景**/ mCanvas.drawBitmap(mbitmapBg,0,0, mPaint); /**绘制小球**/ mCanvas.drawBitmap(mbitmapBall, mPosX,mPosY, mPaint); /**X轴 Y轴 Z轴的重力值**/ mCanvas.drawText("X轴重力值 :" + mGX, 0, 20, mPaint); mCanvas.drawText("Y轴重力值 :" + mGY, 0, 40, mPaint); mCanvas.drawText("Z轴重力值 :" + mGZ, 0, 60, mPaint); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceCreated(SurfaceHolder holder) { /**开始游戏主循环线程**/ mIsRunning = true; new Thread(this).start(); /**得到当前屏幕宽高**/ mScreenWidth = this.getWidth(); mScreenHeight = this.getHeight(); /**得到小球越界区域**/ mScreenBallWidth = mScreenWidth - mbitmapBall.getWidth(); mScreenBallHeight = mScreenHeight - mbitmapBall.getHeight(); } @Override public void surfaceDestroyed(SurfaceHolder holder) { mIsRunning = false; } @Override public void run() { while (mIsRunning) { /** 取得更新游戏之前的时间 **/ long startTime = System.currentTimeMillis(); /** 在这里加上线程安全锁 **/ synchronized (mSurfaceHolder) { /** 拿到当前画布 然后锁定 **/ mCanvas = mSurfaceHolder.lockCanvas(); Draw(); /** 绘制结束后解锁显示在屏幕上 **/ mSurfaceHolder.unlockCanvasAndPost(mCanvas); } /** 取得更新游戏结束的时间 **/ long endTime = System.currentTimeMillis(); /** 计算出游戏一次更新的毫秒数 **/ int diffTime = (int) (endTime - startTime); /** 确保每次更新时间为50帧 **/ while (diffTime <= TIME_IN_FRAME) { diffTime = (int) (System.currentTimeMillis() - startTime); /** 线程等待 **/ Thread.yield(); } } } @Override public void onAccuracyChanged(Sensor arg0, int arg1) { // TODO Auto-generated method stub } @Override public void onSensorChanged(SensorEvent event) { mGX = event.values[SensorManager.DATA_X]; mGY= event.values[SensorManager.DATA_Y]; mGZ = event.values[SensorManager.DATA_Z]; //这里乘以2是为了让小球移动的更快 mPosX -= mGX * 2; mPosY += mGY * 2; //检测小球是否超出边界 if (mPosX < 0) { mPosX = 0; } else if (mPosX > mScreenBallWidth) { mPosX = mScreenBallWidth; } if (mPosY < 0) { mPosY = 0; } else if (mPosY > mScreenBallHeight) { mPosY = mScreenBallHeight; } } } } 这时用重力感应器控制小球移动的一个demo,但是现在我想自己画一个圆充当小球,而不是用图片替代,我该怎么改这段代码?求指教!
安卓opencv mat转bitmap停止运行
纯新手 刚接触三天不到 用opencv做拍照 可是抓取图像之后不能转为bitmap在imageview中显示 Utils.matToBitmap(mTmp,bit); 一直卡在这一句 跪求大大们指点 不知道代码有没有用 贴上来再说 顺便求问一下我的cameraview旋转之后没有全屏 这是为什么 怎么弄啊 protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); // 删除标题 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // 设置全屏 setContentView(R.layout.activity_main); but=(Button)findViewById(R.id.pai); img=(ImageView)findViewById(R.id.img); but.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (IsStart==true){ IsStart=false; mTmp=mRgbaT; mOpenCvCameraView.disableView(); bit=Bitmap.createBitmap(mTmp.height(),mTmp.width(), Bitmap.Config.ARGB_8888); Utils.matToBitmap(mTmp,bit); img.setImageBitmap(bit); //Intent intent=new Intent(); //intent.setClass(MainActivity.this,MainActivity.class); // intent.putExtra("bitmap", bit); //startActivity(intent); } else{ IsStart=true; mOpenCvCameraView.enableView(); } } }); mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.activity_camera_view); // 绑定摄像头控件 mOpenCvCameraView.setCvCameraViewListener(this); mOpenCvCameraView.enableView(); } public void onCameraViewStarted(int width, int height) { mRgba = new Mat(height, width, CvType.CV_8UC4); // 为图像帧数据申请空间,8位4通道图像,包括透明alpha通道 mRgbaT=new Mat(height, width, CvType.CV_8UC4); mTmp=new Mat(height, width, CvType.CV_8UC4); } public void onCameraViewStopped() { mRgba.release(); // 回收帧数据 } public Mat onCameraFrame(CvCameraViewFrame inputFrame) { mRgba = inputFrame.rgba(); // 获取摄像头前景图像 Mat rotateMat=Imgproc.getRotationMatrix2D(new Point(mRgba.rows()/2,mRgba.cols()/2), -90, 1); Imgproc.warpAffine(mRgba,mRgbaT,rotateMat,mRgbaT.size()); return mRgbaT; }
如何在Service中改变设置屏幕亮度Alpha
写了个开机自启动的Service 主要就是监控其他应用是否 横屏、全屏 在Service中添加一个不可见的View监控是否全屏 这个实现了 就是还要实现在横屏且全屏状态下设置手机屏幕透明度 activity中设置如下: Window window =getWindow(); WindowManager.LayoutParams lp = window.getAttributes(); lp.alpha = light; window.setAttributes(lp); 但是getWindow()只能在Activity中调用 要如何在Service中设置
请问mpandroidchart如何实现动画连续不断的重载,动画如何暂停
新手程序员一枚,现在需要我要做一个连续不断的波形图,因为要实现手势操作,所以采用了mpandroidchart ,我在示例代码上面进行改动的,但是我无论如何只能实现一次动画效果。求大神们帮助,现在附上代码 public class LineWaveActivity extends DemoBase implements OnSeekBarChangeListener, OnChartGestureListener, OnChartValueSelectedListener { private LineChart mChart; private SeekBar mSeekBarX, mSeekBarY; private TextView tvX, tvY; // -----------------波形曲线可能会用到的参数(尖波)-------------- private List<Map<String, Object>> month = new ArrayList<Map<String, Object>>(); private List<Map<String, Object>> data = new ArrayList<Map<String, Object>>(); // 数据 // x轴数据——单位秒(s) private String[] mTimes = new String[] { "00:00s", "00:10s", "00:20s", "00:30s", "00:40s", "00:50s", "00:60s", "00:70s", "00:80s", "00:90s", "00:10s", "01:10s", "01:20s", "01:30s", "01:40s", "01:50s", "01:60s", "01:70s", "01:80s", "01:90s", "02:00s", "02:10s", "02:20s", "02:30s", "02:40s", "02:50s", "02:60s", "02:70s", "02:80s", "02:90s", "03:00s", "03:10s", "03:20s", "03:30s", "03:40s", "03:50s", "03:60s", "03:70s", "03:80s", "03:90s", "04:00s", "04:10s", "04:20s", "04:30s", "04:40s", "04:50s", "04:60s", "04:70s", "04:80s", "04:90s", "05:00s", "05:10s", "05:20s", "05:30s", "05:40s", "05:50s", "05:60s", "05:70s", "05:80s", "05:90s", "06:00s" }; // y轴数据——单位(n/m^2) private int[] arrs = { 0, 0, 0, 0, 0, 0, 5, -10, 15, -20, 25, -25, 20, -15, 10, -5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, -10, 15, -20, 25, -25, 20, -15, 10, -5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, -10, 15, -20, 25, -25, 20, -15, 10, -5, 0, 0, 0, 0, 0 }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 设置窗体全屏 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_linechart); // ---------------波形曲线操作代码块---------------------- Map<String, Object> map = null; for (int i = 0; i < mTimes.length; i++) { map = new HashMap<String, Object>(); map.put("times", mTimes[i]); month.add(map); } Map<String, Object> dataMap = null; for (int i = 0; i < arrs.length; i++) { dataMap = new HashMap<String, Object>(); dataMap.put("ranges", arrs[i]); data.add(dataMap); } // ---------------波形曲线操作代码块---------------------- tvX = (TextView) findViewById(R.id.tvXMax); tvY = (TextView) findViewById(R.id.tvYMax); mSeekBarX = (SeekBar) findViewById(R.id.seekBar1); mSeekBarY = (SeekBar) findViewById(R.id.seekBar2); mSeekBarX.setProgress(250); mSeekBarY.setProgress(100); mSeekBarY.setOnSeekBarChangeListener(this); mSeekBarX.setOnSeekBarChangeListener(this); mChart = (LineChart) findViewById(R.id.chart1); // ChartGestureListener手势监听器,可以使得 chart与手势操作进行交互。 mChart.setOnChartGestureListener(this); // 设置表格上的点,被点击的时候,的回调函数 mChart.setOnChartValueSelectedListener(this); // 设置图表内格子背景是否显示,默认是false mChart.setDrawGridBackground(false); // 数据描述 // 如果没有数据的时候,会显示这个"You need to provide data for the chart.",类似listview的emtpyview mChart.setDescription(""); mChart.setNoDataTextDescription("你需要为图表添加必要的数据!"); // 设置点击value的时候,是否高亮显示 mChart.setHighlightEnabled(true); // 设置是否可以手势操作 mChart.setTouchEnabled(true); // 启用/禁用拖动(平移)图表。 mChart.setDragEnabled(true); // 启用/禁用缩放图表上的两个轴。 mChart.setScaleEnabled(true); // 启用/禁用x轴缩放 mChart.setScaleXEnabled(true); // 启用/禁用y轴缩放 mChart.setScaleYEnabled(true); // 如果设置为false,那么x轴,y轴可以分别放大 mChart.setPinchZoom(false); // 设置背景颜色 // mChart.setBackgroundColor(Color.GRAY); MyMarkerView mv = new MyMarkerView(this, R.layout.custom_marker_view); mChart.setMarkerView(mv); // 设置x轴相关参数 LimitLine llXAxis = new LimitLine(10f, "警戒线"); llXAxis.setLineWidth(4f); llXAxis.enableDashedLine(10f, 10f, 10f); llXAxis.setLabelPosition(LimitLabelPosition.RIGHT_BOTTOM); llXAxis.setTextSize(10f); XAxis xAxis = mChart.getXAxis(); // xAxis.setValueFormatter(new MyCustomXAxisValueFormatter()); // xAxis.addLimitLine(llXAxis); // add x-axis limit line Typeface tf = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf"); LimitLine ll1 = new LimitLine(50f, "Upper Limit"); // 设置警戒线粗细 ll1.setLineWidth(10f); // 设置警戒线间隔大小(间隔宽度,线段位置,线段宽度) ll1.enableDashedLine(40f, 40f, 40f); ll1.setLabelPosition(LimitLabelPosition.RIGHT_TOP); ll1.setTextSize(10f); // 设置字体样式 ll1.setTypeface(tf); LimitLine ll2 = new LimitLine(-50f, "Lower Limit"); ll2.setLineWidth(10f); ll2.enableDashedLine(40f, 40f, 40f); ll2.setLabelPosition(LimitLabelPosition.RIGHT_BOTTOM); ll2.setTextSize(10f); ll2.setTypeface(tf); YAxis leftAxis = mChart.getAxisLeft(); leftAxis.removeAllLimitLines(); // reset all limit lines to avoid // overlapping lines leftAxis.addLimitLine(ll1); leftAxis.addLimitLine(ll2); // 设置y轴最大值 leftAxis.setAxisMaxValue(50f); // 设置y轴最小值 leftAxis.setAxisMinValue(-50f); // 设置y轴起始点是否为0 leftAxis.setStartAtZero(false); // leftAxis.setYOffset(20f); // 设置横向表格为虚线 leftAxis.enableGridDashedLine(10f, 10f, 0f); leftAxis.setDrawLimitLinesBehindData(true); // 设置隐藏右边的坐标轴 mChart.getAxisRight().setEnabled(false); // 设置相对于x,y的放大倍率 // mChart.getViewPortHandler().setMaximumScaleY(20f); // mChart.getViewPortHandler().setMaximumScaleX(20f); // mChart.setVisibleXRange(20);//设置频幕能显示点的数量,要和MAX和Min结合起来使用 // mChart.setVisibleYRange(20f, AxisDependency.LEFT); // mChart.centerViewTo(20, 50, AxisDependency.LEFT); //设置绘图事件,单位——毫秒,绘图程序入口!!!!!!!!!!!!! setData(45, 100); mChart.animateX(6000, Easing.EasingOption.EaseInOutQuart); mChart.invalidate();// 界面刷新 Legend l = mChart.getLegend(); // l.setPosition(LegendPosition.LEFT_OF_CHART);//设置中轴线向右移 l.setForm(LegendForm.LINE);// 设置图表最下面显示的类型 } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { tvX.setText("" + (mSeekBarX.getProgress())); tvY.setText("" + (mSeekBarY.getProgress())); setData(mSeekBarX.getProgress(), mSeekBarY.getProgress()); // 刷新图标 mChart.invalidate(); } // 进度条拖动开始时候调用 @Override public void onStartTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } // 进度条拖动完成之后调用 @Override public void onStopTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } private void setData(int count1, int count2) { count1 = month.size(); count2 = data.size(); ArrayList<String> xVals = new ArrayList<String>(); ArrayList<Entry> yVals = new ArrayList<Entry>(); // x轴显示数据操作 for (int i = 0; i < count1; i++) { Map<String, Object> data = month.get(i); xVals.add(data.get("times").toString()); } // y轴显示数据操作 for (int i = 0; i < count2; i++) { Map<String, Object> data2 = data.get(i); yVals.add(new Entry(Integer .parseInt(data2.get("ranges").toString()), i)); } // create a dataset and give it a type LineDataSet set1 = new LineDataSet(yVals, "——————"); set1.setFillAlpha(110);// 设置填充颜色透明度 set1.setFillColor(Color.RED); // 设置线的样式 set1.enableDashedLine(10f, 5f, 0f); // set1.enableDashedHighlightLine(10f, 5f, 0f); set1.setColor(Color.BLACK); set1.setCircleColor(Color.BLACK); set1.setLineWidth(1f); set1.setCircleSize(4f); set1.setDrawCircleHole(true);// 点的圆圈样式,true为空心点,flase为实心点 set1.setValueTextSize(9f); set1.setFillAlpha(65); set1.setFillColor(Color.BLACK); // set1.setDrawFilled(true); // set1.setShader(new LinearGradient(0, 0, 0, mChart.getHeight(), // Color.BLACK, Color.WHITE, Shader.TileMode.MIRROR)); ArrayList<LineDataSet> dataSets = new ArrayList<LineDataSet>(); dataSets.add(set1); // add the datasets // create a data object with the datasets LineData data = new LineData(xVals, dataSets); // set data Log.i("SumLog", "开始为图形设置数据"); mChart.setData(data); } @Override public void onChartGestureStart(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) { Log.i("Gesture", "START"); } @Override public void onChartGestureEnd(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) { Log.i("Gesture", "END, lastGesture: " + lastPerformedGesture); if (lastPerformedGesture != ChartTouchListener.ChartGesture.SINGLE_TAP) mChart.highlightValues(null); } @Override public void onChartLongPressed(MotionEvent me) { Log.i("LongPress", "Chart longpressed."); } @Override public void onChartDoubleTapped(MotionEvent me) { Log.i("DoubleTap", "Chart double-tapped."); } @Override public void onChartSingleTapped(MotionEvent me) { Log.i("SingleTap", "Chart single-tapped."); } @Override public void onChartFling(MotionEvent me1, MotionEvent me2, float velocityX, float velocityY) { Log.i("Fling", "Chart flinged. VeloX: " + velocityX + ", VeloY: " + velocityY); } @Override public void onChartScale(MotionEvent me, float scaleX, float scaleY) { Log.i("Scale / Zoom", "ScaleX: " + scaleX + ", ScaleY: " + scaleY); } @Override public void onChartTranslate(MotionEvent me, float dX, float dY) { Log.i("Translate / Move", "dX: " + dX + ", dY: " + dY); } @Override public void onValueSelected(Entry e, int dataSetIndex, Highlight h) { Log.i("Entry selected", e.toString()); Log.i("", "low: " + mChart.getLowestVisibleXIndex() + ", high: " + mChart.getHighestVisibleXIndex()); } @Override public void onNothingSelected() { Log.i("Nothing selected", "Nothing selected."); } } 请问各位,如何实现一个可用按钮控制的连续不断的波形效果,比较急额,卡了四天了
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它是一个过程,是一个不断累积、不断沉淀、不断总结、善于传达自己的个人见解以及乐于分享的过程。
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过...
前端 | 2. 正则
转载请注明以下: 本文转自清自以敬的博客:https://blog.csdn.net/qq_45791147 文章目录1.转义2.正则表达式初步2.1.匹配字符2.1.1.组成元素2.1.2.基础正则的设计 1.转义 转义的作用: 当某个字符在表达式中具有特殊含义,例如字符串引号中出现了引号,为了可以使用这些字符本身,而不是使用其在表达式中的特殊含义,则需要通过转义符“\”来构建该字符转义...
有哪些让程序员受益终生的建议
从业五年多,辗转两个大厂,出过书,创过业,从技术小白成长为基层管理,联合几个业内大牛回答下这个问题,希望能帮到大家,记得帮我点赞哦。 敲黑板!!!读了这篇文章,你将知道如何才能进大厂,如何实现财务自由,如何在工作中游刃有余,这篇文章很长,但绝对是精品,记得帮我点赞哦!!!! 一腔肺腑之言,能看进去多少,就看你自己了!!! 目录: 在校生篇: 为什么要尽量进大厂? 如何选择语言及方...
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...
linux系列之常用运维命令整理笔录
本博客记录工作中需要的linux运维命令,大学时候开始接触linux,会一些基本操作,可是都没有整理起来,加上是做开发,不做运维,有些命令忘记了,所以现在整理成博客,当然vi,文件操作等就不介绍了,慢慢积累一些其它拓展的命令,博客不定时更新 free -m 其中:m表示兆,也可以用g,注意都要小写 Men:表示物理内存统计 total:表示物理内存总数(total=used+free) use...
比特币原理详解
一、什么是比特币 比特币是一种电子货币,是一种基于密码学的货币,在2008年11月1日由中本聪发表比特币白皮书,文中提出了一种去中心化的电子记账系统,我们平时的电子现金是银行来记账,因为银行的背后是国家信用。去中心化电子记账系统是参与者共同记账。比特币可以防止主权危机、信用风险。其好处不多做赘述,这一层面介绍的文章很多,本文主要从更深层的技术原理角度进行介绍。 二、问题引入 假设现有4个人...
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 IT 类的外包开发,是非标品开发,所以很有可能在开发过程中会有这样那样的需求修改,而这种需求修改很容易造成扯皮,进而影响到费用支付,甚至出现做完了项目收不到钱的情况。 那么,怎么保证自己的薪酬安全呢? 我们在开工前,一定要做好一些证据方面的准备(也就是“讨薪”的理论依据),这其中最重要的就是需求文档和验收标准。一定要让需求方提供这两个文档资料作为开发的基础。之后开发...
网页实现一个简单的音乐播放器(大佬别看。(⊙﹏⊙))
今天闲着无事,就想写点东西。然后听了下歌,就打算写个播放器。 于是乎用h5 audio的加上js简单的播放器完工了。 演示地点演示 html代码如下` music 这个年纪 七月的风 音乐 ` 然后就是css`*{ margin: 0; padding: 0; text-decoration: none; list-...
Python十大装B语法
Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。
数据库优化 - SQL优化
以实际SQL入手,带你一步一步走上SQL优化之路!
2019年11月中国大陆编程语言排行榜
2019年11月2日,我统计了某招聘网站,获得有效程序员招聘数据9万条。针对招聘信息,提取编程语言关键字,并统计如下: 编程语言比例 rank pl_ percentage 1 java 33.62% 2 cpp 16.42% 3 c_sharp 12.82% 4 javascript 12.31% 5 python 7.93% 6 go 7.25% 7 p...
通俗易懂地给女朋友讲:线程池的内部原理
餐盘在灯光的照耀下格外晶莹洁白,女朋友拿起红酒杯轻轻地抿了一小口,对我说:“经常听你说线程池,到底线程池到底是个什么原理?”
《奇巧淫技》系列-python!!每天早上八点自动发送天气预报邮件到QQ邮箱
将代码部署服务器,每日早上定时获取到天气数据,并发送到邮箱。 也可以说是一个小型人工智障。 知识可以运用在不同地方,不一定非是天气预报。
经典算法(5)杨辉三角
杨辉三角 是经典算法,这篇博客对它的算法思想进行了讲解,并有完整的代码实现。
腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹?
昨天,有网友私信我,说去阿里面试,彻底的被打击到了。问了为什么网上大量使用ThreadLocal的源码都会加上private static?他被难住了,因为他从来都没有考虑过这个问题。无独有偶,今天笔者又发现有网友吐槽了一道腾讯的面试题,我们一起来看看。 腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹? 在互联网职场论坛,一名程序员发帖求助到。二面腾讯,其中一个算法题:64匹...
面试官:你连RESTful都不知道我怎么敢要你?
干货,2019 RESTful最贱实践
Docker 从入门到掉坑
Docker 介绍 简单的对docker进行介绍,可以把它理解为一个应用程序执行的容器。但是docker本身和虚拟机还是有较为明显的出入的。我大致归纳了一下,可以总结为以下几点: docker自身也有着很多的优点,关于它的优点,可以总结为以下几项: 安装docker 从 2017 年 3 月开始 docker 在原来的基础上分为两个分支版本: Docker CE 和 Doc...
为啥国人偏爱Mybatis,而老外喜欢Hibernate/JPA呢?
关于SQL和ORM的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行了一番讨论,感触还是有一些,于是就有了今天这篇文。 声明:本文不会下关于Mybatis和JPA两个持久层框架哪个更好这样的结论。只是摆事实,讲道理,所以,请各位看官勿喷。 一、事件起因 关于Mybatis和JPA孰优孰劣的问题,争论已经很多年了。一直也没有结论,毕竟每个人的喜好和习惯是大不相同的。我也看...
白话阿里巴巴Java开发手册高级篇
不久前,阿里巴巴发布了《阿里巴巴Java开发手册》,总结了阿里巴巴内部实际项目开发过程中开发人员应该遵守的研发流程规范,这些流程规范在一定程度上能够保证最终的项目交付质量,通过在时间中总结模式,并推广给广大开发人员,来避免研发人员在实践中容易犯的错误,确保最终在大规模协作的项目中达成既定目标。 无独有偶,笔者去年在公司里负责升级和制定研发流程、设计模板、设计标准、代码标准等规范,并在实际工作中进行...
SQL-小白最佳入门sql查询一
不要偷偷的查询我的个人资料,即使你再喜欢我,也不要这样,真的不好;
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // doshom...
Nginx 原理和架构
Nginx 是一个免费的,开源的,高性能的 HTTP 服务器和反向代理,以及 IMAP / POP3 代理服务器。Nginx 以其高性能,稳定性,丰富的功能,简单的配置和低资源消耗而闻名。 Nginx 的整体架构 Nginx 里有一个 master 进程和多个 worker 进程。master 进程并不处理网络请求,主要负责调度工作进程:加载配置、启动工作进程及非停升级。worker 进程负责处...
Python 编程开发 实用经验和技巧
Python是一门很灵活的语言,也有很多实用的方法,有时候实现一个功能可以用多种方法实现,我这里总结了一些常用的方法和技巧,包括小数保留指定位小数、判断变量的数据类型、类方法@classmethod、制表符中文对齐、遍历字典、datetime.timedelta的使用等,会持续更新......
YouTube排名第一的励志英文演讲《Dream(梦想)》
Idon’t know what that dream is that you have, I don't care how disappointing it might have been as you've been working toward that dream,but that dream that you’re holding in your mind, that it’s po...
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,...
程序员:我终于知道post和get的区别
是一个老生常谈的话题,然而随着不断的学习,对于以前的认识有很多误区,所以还是需要不断地总结的,学而时习之,不亦说乎
《程序人生》系列-这个程序员只用了20行代码就拿了冠军
你知道的越多,你不知道的越多 点赞再看,养成习惯GitHub上已经开源https://github.com/JavaFamily,有一线大厂面试点脑图,欢迎Star和完善 前言 这一期不算《吊打面试官》系列的,所有没前言我直接开始。 絮叨 本来应该是没有这期的,看过我上期的小伙伴应该是知道的嘛,双十一比较忙嘛,要值班又要去帮忙拍摄年会的视频素材,还得搞个程序员一天的Vlog,还要写BU...
程序员把地府后台管理系统做出来了,还有3.0版本!12月7号最新消息:已在开发中有github地址
第一幕:缘起 听说阎王爷要做个生死簿后台管理系统,我们派去了一个程序员…… 996程序员做的梦: 第一场:团队招募 为了应对地府管理危机,阎王打算找“人”开发一套地府后台管理系统,于是就在地府总经办群中发了项目需求。 话说还是中国电信的信号好,地府都是满格,哈哈!!! 经常会有外行朋友问:看某网站做的不错,功能也简单,你帮忙做一下? 而这次,面对这样的需求,这个程序员...
网易云6亿用户音乐推荐算法
网易云音乐是音乐爱好者的集聚地,云音乐推荐系统致力于通过 AI 算法的落地,实现用户千人千面的个性化推荐,为用户带来不一样的听歌体验。 本次分享重点介绍 AI 算法在音乐推荐中的应用实践,以及在算法落地过程中遇到的挑战和解决方案。 将从如下两个部分展开: AI算法在音乐推荐中的应用 音乐场景下的 AI 思考 从 2013 年 4 月正式上线至今,网易云音乐平台持续提供着:乐屏社区、UGC...
相关热词 c# 图片上传 c# gdi 占用内存 c#中遍历字典 c#控制台模拟dos c# 斜率 最小二乘法 c#进程延迟 c# mysql完整项目 c# grid 总行数 c# web浏览器插件 c# xml 生成xsd
立即提问