Android Basics Summary (ix)

Source: Internet
Author: User
Tags gety

Multimedia Concepts (Understanding)
    • Text, pictures, audio, video
Calculation of computer picture size (master)

Picture size = Total pixels of the picture * the size occupied by each pixel

    • Monochrome graphs: 1/8 bytes per pixel
    • 16 Color graphs: 1/2 bytes per pixel
    • 256 Color graphs: 1 bytes per pixel
    • 24-bit graph: 3 bytes per pixel
Load large picture into memory (master)

The Android system represents each pixel in argb, so each pixel occupies 4 bytes and is prone to memory overflow

Zoom in on a picture (master)
    • 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 scale

      //设置缩放比例opts.inSampleSize = scale;//为图片申请内存opts.inJustDecodeBounds = false;Bitmap bm = BitmapFactory.decodeFile("sdcard/dog.jpg", opts);iv.setImageBitmap(bm);
Create a copy of the picture in memory (master)

The directly loaded bitmap object is read-only and cannot be modified, and the image can only be modified in memory to create an identical bitmap copy, and then modify 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);
Special effects on images (familiar)
    • 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 (Master)

Record the XY coordinates of the user touch event, draw a line * to ImageView set touch listening, get the user's touch event, and learn the user 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 screen://Users swipe their fingers, coordinate changes constantly, get the latest coordinates int newx = (int) E                Vent.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, changing 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);
    • Every time the system receives the SD card ready broadcast, it will go through all the files and folders of the SD card, and all the multimedia files that are traversed are saved in the Mediastore database with an index that contains the file name, path, size of the multimedia files.
    • Each time the gallery is opened, it does not traverse the SD card to get the picture, but rather the content provider obtains the picture from the Mediastore database and then reads the picture
    • When the system is powered on or when the SD card button is loaded, 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 (mastering)
    • Principle: Put on the underwear and wear the photos overlap display, underwear in the following, the user swipe the screen, the touch is the coat, the fingers pass through the pixels are set to transparent, underwear photos show out

       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;    }});
    • Setting one pixel at a time is too slow to touch the center of the pixel, with a radius of 5 to draw the circle, and the pixels in the circle to be all 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 Play Service (master)
    • The code that plays the audio should run in the service and 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 (master)
  • 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 kept, constantly refresh the progress bar, using the timer every 500 milliseconds to get the playback progress
  • Send a message to handler, put the playback progress into the Message object, update the progress of the Seekbar 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 (familiar) Surfaceview
  • High demand for real-time updates to the screen
  • Double buffering technology: There are two canvases in memory, a canvas is displayed to the screen, B canvas draws the next frame in memory, B is displayed to the screen after drawing, a continues to draw the next frame in memory
  • Play video is also used MediaPlayer, but unlike audio, to set the display in which Surfaceview

    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 status 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    }});
  • Once the Surfaceview is not visible, it will be destroyed and once visible, it will be created, stopped when destroyed, and played again when it is created again.
Webcam (familiar)
    • 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);
Use the camera class to complete a photo (familiar)
    • Consult a document

Android Basics Summary (ix)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.