Multimedia concepts
Writing, drawing, audio, video
Calculate Computer image size
Image size = Image total pixels * size of each pixel occupies
Monochrome graphs: 1/8 bytes per pixel
16 Color Graph: 1/2 bytes per pixel
256 Color graph: 1 bytes per pixel
24-bit graph: 3 bytes per pixel
Load large images into memory
The Android system uses ARGB to represent every pixel, so each pixel occupies 4 bytes, very easy memory overflow
Zoom to a picture
Get Screen width height
Display dp = getWindowManager().getDefaultDisplay();int screenWidth = dp.getWidth();int screenHeight = dp.getHeight();
Get Picture Width height
Options opts = new Options();//请求图片属性但不申请内存opts.inJustDecodeBounds = true;BitmapFactory.decodeFile("sdcard/dog.jpg", opts);int imageWidth = opts.outWidth;int imageHeight = opts.outHeight;
The width of the picture, divided by the width of the screen, calculates a wide and high scale, and takes a larger value as the scale of the picture.
int scale = 1;int scaleX = imageWidth / screenWidth;int scaleY = imageHeight / screenHeight;if(scaleX >= scaleY && scaleX > 1){ scale = scaleX;}else if(scaleY > scaleX && scaleY > 1){ scale = scaleY;}
Load pictures by Zoom scale
//设置缩放比例opts.inSampleSize = scale;//为图片申请内存opts.inJustDecodeBounds = false;Bitmap bm = BitmapFactory.decodeFile("sdcard/dog.jpg", opts);iv.setImageBitmap(bm);
Create a copy of a picture in memory
The directly loaded bitmap object is read-only. cannot be changed. To change a picture you can only create an identical copy of bitmap in memory. Then change the copy.
//载入原图 Bitmap srcBm = BitmapFactory.decodeFile("sdcard/photo3.jpg"); iv_src.setImageBitmap(srcBm); //创建与原图大小一致的空白bitmap Bitmap copyBm = Bitmap.createBitmap(srcBm.getWidth(), srcBm.getHeight(), srcBm.getConfig()); //定义画笔 Paint paint = new Paint(); //把纸铺在画版上 Canvas canvas = new Canvas(copyBm); //把srcBm的内容绘制在copyBm上 canvas.drawBitmap(srcBm, new Matrix(), paint); iv_copy.setImageBitmap(copyBm);
Make special effects on images
First define a Matrix object
Matrix mt = new Matrix();
Zoom effect
//x轴缩放1倍,y轴缩放0.5倍mt.setScale(1, 0.5f);
Rotation effect
//以copyBm.getWidth() / 2, copyBm.getHeight() / 2点为轴点,顺时旋转30度mt.setRotate(30, copyBm.getWidth() / 2, copyBm.getHeight() / 2);
Translation
//x轴坐标+10,y轴坐标+20mt.setTranslate(10, 20);
Mirror
//把X坐标都变成负数mt.setScale(-1, 1);//图片总体向右移mt.postTranslate(copyBm.getWidth(), 0);
Reflection
//把Y坐标都变成负数mt.setScale(1, -1);//图片总体向下移mt.postTranslate(0, copyBm.getHeight());
Drawing board
Record the XY coordinates of user touch events, draw lines
- Set the touch listener to ImageView, get the user's touch event, and learn the user's touch ImageView coordinates
Iv.setontouchlistener (New Ontouchlistener () {@Override public boolean onTouch (View V, Motion Event event) {//TODO auto-generated Method Stub switch (event.getaction ()) {//Touch screen Case Motionevent.action_down://get touch screen when finger coordinates startX = (int) event.getx (); Starty = (int) event.gety (); Break Swipe case Motionevent.action_move on the screen://user swipe finger. Coordinates are constantly changing to get the latest coordinates int newx = (int) event.getx (); int newy = (int) event.gety (); The coordinates obtained by the last Ontouch method and the coordinates obtained are plotted in a straight line canvas.drawline (StartX, Starty, newx, newy, paint); Iv.setimagebitmap (COPYBM); StartX = newx; Starty = Newy; Break } return true; } });
Brush effect, Bold brush
paint.setStrokeWidth(8);
Palette. Change brush Color
paint.setColor(Color.GREEN);
Save picture to SD card
FileOutputStream fos = null;try { fos = new FileOutputStream(new File("sdcard/dazuo.png"));} catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace();}//保存图片copyBm.compress(CompressFormat.PNG, 100, fos);
Each time the system receives an SD card ready broadcast. Will go through all the files and directories of the SD card, and all the multimedia files that have been traversed are stored in an index in the Mediastore database. This index includes the file name, path, size of the multimedia file
Each time the gallery is opened. Does not go through the SD card to get pictures. Instead, the content provider obtains information about the picture from the Mediastore database, and then reads the picture
When the system is powered on or clicks on the SD card button, the system sends an SD card ready broadcast, and we can send the ready broadcast manually.
Intent intent = new Intent();intent.setAction(Intent.ACTION_MEDIA_MOUNTED);intent.setData(Uri.fromFile(Environment.getExternalStorageDirectory()));sendBroadcast(intent);
Tearing clothes
Principle: The picture that wears underwear and wears a coat overlaps to display. The underwear shines below, when the user slides the screen. Touch is the coat. The pixels passing through the fingers are set to transparent. The underwear is showing.
iv.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_MOVE: int newX = (int) event.getX(); int newY = (int) event.getY(); //把指定的像素变成透明 copyBm.setPixel(newX, newY, Color.TRANSPARENT); iv.setImageBitmap(copyBm); break; } return true; }});
Just set one pixel at a time is too slow to touch the center of the pixel. Radius of 5 Draws a circle, the pixels within the circle are all set to transparent
for (int i = -5; i < 6; i++) { for (int j = -5; j < 6; j++) { if(Math.sqrt(i * i + j * j) <= 5) copyBm.setPixel(newX + i, newY + j, Color.TRANSPARENT); }}
Music player Playback Service
- The code that plays the audio should be executed in the service. Define a playback service Musicservice
Service definition play, stop, pause, Continueplay and other methods
private void play() { // TODO Auto-generated method stub player.reset(); try { player.setDataSource("sdcard/bzj.mp3"); player.prepare(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } player.start(); } private void pause() { player.pause(); } private void stop() { player.stop(); } private void continuePlay() { player.start(); }
To extract these methods into an interface Musicinterface
Define an intermediate human, inherit binder, implement Musicinterface
Start Musicservice First, then bind
Intent intent = new Intent(this, MusicService.class);startService(intent);bindService(intent, conn, BIND_AUTO_CREATE);
Set progress bar based on playback progress
Gets the current playback time and the maximum time of the current audio
int currentPosition = player.getCurrentPosition();int duration = player.getDuration();
Playback progress needs to be constantly acquired. Constantly refresh the progress bar. Use timers to get playback progress every 500 milliseconds
Send a message to handler. Put the playback progress into the Message object and update the Seekbar progress in handler
Timer timer = new Timer();timer.schedule(new TimerTask() { @Override public void run() { int currentPosition = player.getCurrentPosition(); int duration = player.getDuration(); Message msg = Message.obtain(); //把播放进度存入Message中 Bundle data = new Bundle(); data.putInt("currentPosition", currentPosition); data.putInt("duration", duration); msg.setData(data); MainActivity.handler.sendMessage(msg); }}, 5, 500);
Define handler in activity
static Handler handler = new Handler(){ public void handleMessage(android.os.Message msg) { //取出消息携带的数据 Bundle data = msg.getData(); int currentPosition = data.getInt("currentPosition"); int duration = data.getInt("duration"); //设置播放进度 sb.setMax(duration); sb.setProgress(currentPosition); };};
Drag the progress bar to change the playback progress //给sb设置一个拖动侦听 sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { //停止拖动时调用 @Override public void onStopTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub int progress = seekBar.getProgress(); mi.seekTo(progress); } //開始拖动时调用 @Override public void onStartTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } //拖动的时候不断调用 @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { // TODO Auto-generated method stub
Video Player Surfaceview
- High demand for real-time updates to the screen
- Dual Buffering technology: There are two canvases in memory, a canvas is displayed to the screen, and the B canvas draws the next frame in memory. After drawing is finished, B is displayed to the screen, a continues to draw the next frame in memory.
Play video is also used MediaPlayer. Just unlike audio, to set which surfaceview to display in
SurfaceView sv = (SurfaceView) findViewById(R.id.sv);SurfaceHolder sh = sv.getHolder();MediaPlayer player = new MediaPlayer();player.reset();try { player.setDataSource("sdcard/2.3gp"); player.setDisplay(sh); player.prepare();} catch (Exception e) { e.printStackTrace();}player.start();
Surfaceview is a heavyweight component that is created when it is visible
Set callback for Surfaceholder. Similar to listening. To know the state of Surfaceview.
sh.addCallback(new Callback() { //SurfaceView销毁时调用 @Override public void surfaceDestroyed(SurfaceHolder holder) { // TODO Auto-generated method stub } //SurfaceView创建时调用 @Override public void surfaceCreated(SurfaceHolder holder) { // TODO Auto-generated method stub } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // TODO Auto-generated method stub }});
Surfaceview once not visible. Will be destroyed once it is visible. will be created. Stop playback when destroying. Start playing again when you create it again
Camera
Start the system-provided camera program
//隐式启动系统提供的拍照ActivityIntent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//设置照片的保存路径File file = new File(Environment.getExternalStorageDirectory(), "haha.jpg"); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)); startActivityForResult(intent, 0);
Start the camera program provided by the system
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);File file = new File(Environment.getExternalStorageDirectory(), "haha.3gp"); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)); //设置保存视频文件的质量intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);startActivityForResult(intent, 0);
Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.
Andrews----Multimedia Programming