resize the preview size as the ratio of picture size
[rtmpclient.git] / app / src / main / java / ai / suanzi / rtmpclient / CameraView.java
1 package ai.suanzi.rtmpclient;
2
3 import android.content.Context;
4 import android.view.SurfaceHolder;
5 import android.view.SurfaceView;
6 import android.widget.FrameLayout;
7
8 import org.apache.log4j.Logger;
9
10 public class CameraView extends SurfaceView implements SurfaceHolder.Callback {
11
12     private static Logger gLogger = Logger.getLogger("CameraView");
13     public static int SCREEN_WIDTH;
14     public static int SCREEN_HEIGHT;
15
16     private Context mContext;
17     private SurfaceHolder mHolder;
18     private Callback mCallback;
19     private int width;
20     private int height;
21
22     public CameraView (Context context, Callback cb) {
23         super(context);
24         this.mContext = context;
25         mHolder = this.getHolder();
26         mHolder.addCallback(this);
27         this.mCallback = cb;
28     }
29
30     public void setLayout(int width, int heitht){
31         this.height = heitht;
32         this.width = width;
33         gLogger.error("SurfacedCreated, screen size w: " + SCREEN_WIDTH + ", h:" + SCREEN_HEIGHT + ". preview size, w: " + width + ", h: " + height);
34
35         float ratio = (float) height / width; // 3/4,,,  640x480  1008x1344
36         FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams)getLayoutParams();
37         gLogger.error("ratio = " + ratio + ". xxx=" + (float)(SCREEN_HEIGHT / SCREEN_HEIGHT));
38         if(ratio > (float)(SCREEN_HEIGHT / SCREEN_WIDTH) ){
39             lp.width = SCREEN_HEIGHT * width / height;
40             lp.height = SCREEN_HEIGHT;
41             lp.leftMargin = (SCREEN_WIDTH - lp.width ) / 2;
42             lp.topMargin = 0;
43         } else {
44             lp.width = SCREEN_WIDTH;
45             lp.height = SCREEN_WIDTH * height / width;
46             lp.leftMargin = 0;
47             lp.topMargin = (SCREEN_HEIGHT - lp.height) / 2;
48         }
49         this.setLayoutParams(lp);
50     }
51
52     // SurfaceHolder.Callback implementation
53     @Override
54     public void surfaceCreated(final SurfaceHolder holder){
55         gLogger.error("SurfacedCreated, screen size w: " + SCREEN_WIDTH + ", h:" + SCREEN_HEIGHT + ". preview size, w: " + width + ", h: " + height);
56     }
57
58     @Override
59     public void surfaceChanged(SurfaceHolder holder, int format, int widht, int height){
60         gLogger.error("surfaceChanged");
61         mHolder = holder;
62         mCallback.onSurfaceChanged(holder, format, widht, height);
63     }
64
65     @Override
66     public void surfaceDestroyed(SurfaceHolder holder){ gLogger.debug("surfaceDestroyed");
67     }
68
69     public interface Callback {
70         void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height);
71     }
72 }