Android视频的放大和缩小

来源:互联网 发布:三国志11古武将数据 编辑:程序博客网 时间:2024/05/17 16:02

Android视频的放大和缩小

这个还是在很久以前的时候写的,当时公司有一个需求,就是需要仿360或者是小蚁的app,做一个视频的放大缩小,当时是搜遍了,搜到的都是关于图片的放大缩小等,无奈之下,就自己去研究了一下,布局啊,自定义控件啊,手势啊,话说好久都没有做过纯上层的开发,现在做的智能家居一块的产品,更多的是倾向于底层着一块的实现,现在趁还没有怎么忘记,就把当时写的东西粘出来分享出来吧,希望能给大家啊一点小的帮助;
主要涉及到的东西就是滑动的算法,onLayout的使用,android系统手势的操作,自定义控件的开发等。
也写了好久了:不赘述,直接上代码:

这是自定义的CustomSurfaceView

package com.example.surfaceviewdemo;import android.content.Context;import android.util.AttributeSet;import android.util.FloatMath;import android.util.Log;import android.view.GestureDetector;import android.view.Gravity;import android.view.MotionEvent;import android.view.ScaleGestureDetector;import android.view.SurfaceView;import android.view.View;import android.view.ViewConfiguration;import android.widget.LinearLayout;import android.widget.LinearLayout.LayoutParams;public class CustomSurfaceView extends SurfaceView {    public static final String TAG = "MyGesture";    GestureDetector mGestureDetector = null;    ScaleGestureDetector scaleGestureDetector = null;    private int screenHeight = 0;    private int screenWidth = 0;    /** 记录是拖拉照片模式还是放大缩小照片模式 */    private int mode = 0;// 初始状态    /** 拖拉照片模式 */    private static final int MODE_DRAG = 1;    /** 放大缩小照片模式 */    private static final int MODE_ZOOM = 2;    private static final int MODE_DOUBLE_CLICK = 3;    private long firstTime = 0;    private static final float SCALE_MAX = 4.0f;    private static float touchSlop = 0;    private int start_Top = -1, start_Right = -1, start_Left = -1, start_Bottom = -1;    private int start_x, start_y, current_x, current_y;    View view;    private int View_Width = 0;    private int View_Height = 0;    private int initViewWidth = 0;    private int initViewHeight = 0;    private int fatherView_W;    private int fatherView_H;    private int fatherTop;    private int fatherBottom;    int distanceX = 0;    int distanceY = 0;    private boolean isControl_Vertical = false;    private boolean isControl_Horizal = false;    private float ratio = 0.3f;    public CustomSurfaceView(Context context, AttributeSet attrs, int defStyle) {        super(context, attrs, defStyle);        init();    }    public CustomSurfaceView(Context context, AttributeSet attrs) {        super(context, attrs);        init();    }    public CustomSurfaceView(Context context) {        super(context);        init();    }    @SuppressWarnings("deprecation")    private void init() {        touchSlop = ViewConfiguration.getTouchSlop();        this.setFocusable(true);        this.setClickable(true);        this.setLongClickable(true);        view = CustomSurfaceView.this;        screenHeight = ScreenUtils.getScreenHeight(getContext());        screenWidth = ScreenUtils.getScreenWidth(getContext());        scaleGestureDetector = new ScaleGestureDetector(getContext(), new simpleScaleGestueListener());        mGestureDetector = new GestureDetector(new simpleGestureListener());    }    @Override    public boolean onTouchEvent(MotionEvent event) {        mGestureDetector.onTouchEvent(event);        switch (event.getAction() & MotionEvent.ACTION_MASK) {        case MotionEvent.ACTION_DOWN:            onTouchDown(event);            break;        case MotionEvent.ACTION_POINTER_DOWN:            onPointerDown(event);            break;        case MotionEvent.ACTION_MOVE:            onTouchMove(event);            break;        case MotionEvent.ACTION_UP:            mode = 0;            break;        case MotionEvent.ACTION_POINTER_UP:            mode = 0;            break;        default:            break;        }        return scaleGestureDetector.onTouchEvent(event);    }    /**     * 滑动事件分发     *      * @param event     */    private void onTouchMove(MotionEvent event) {        int left = 0, top = 0, right = 0, bottom = 0;        if (mode == MODE_DRAG) {            left = getLeft();            right = getRight();            top = getTop();            bottom = getBottom();            distanceX = (int) (event.getRawX() - current_x);            distanceY = (int) (event.getRawY() - current_y);            if(icallBack!=null){                icallBack.getAngle((int)getX(),this.getWidth());            }            if (touchSlop <= getDistance(distanceX, distanceY)) {                left = left + distanceX;                right = right + distanceX;                bottom = bottom + distanceY;                top = top + distanceY;                // 水平判断                if (isControl_Horizal) {                    if (left >= 0) {                        left = 0;                        right = this.getWidth();                    }                    if (right <= screenWidth) {                        left = screenWidth - this.getWidth();                        right = screenWidth;                    }                } else {                    left = getLeft();                    right = getRight();                }                // 垂直判断                if (isControl_Vertical) {                    if (top > 0) {                        top = 0;                        bottom = this.getHeight();                    }                    if (bottom <= start_Bottom) {                        bottom = start_Bottom;                        top = fatherView_H - this.getWidth();                    }                } else {                    top = this.getTop();                    bottom = this.getBottom();                }                if (isControl_Horizal || isControl_Vertical) {                    this.setPosition(left, top, right, bottom);                }                current_x = (int) event.getRawX();                current_y = (int) event.getRawY();            }        }    }    /**     * 多点触控时     *      * @param event     */    private void onPointerDown(MotionEvent event) {        if (event.getPointerCount() == 2) {            mode = MODE_ZOOM;        }    }    /**     * 按下时的事件     *      * @param event     */    private void onTouchDown(MotionEvent event) {        mode = MODE_DRAG;        start_x = (int) event.getRawX();        start_y = (int) event.getRawY();        current_x = (int) event.getRawX();        current_y = (int) event.getRawY();        View_Width = getWidth();        View_Height = getHeight();        if (View_Height > fatherView_H) {            isControl_Vertical = true;        } else {            isControl_Vertical = false;        }        if (View_Width > fatherView_W) {            isControl_Horizal = true;        } else {            isControl_Horizal = false;        }    }    @Override    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {        super.onLayout(changed, left, top, right, bottom);        if (start_Top == -1) {            start_Top = top;            start_Left = left;            start_Right = right;            start_Bottom = bottom;            initViewWidth = view.getWidth();            initViewHeight = view.getHeight();        }    }    /**     * 缩放手势的监听事件     *      * @author Administrator     *      */    private class simpleScaleGestueListener implements ScaleGestureDetector.OnScaleGestureListener {        // 用到的放大缩小的方法        @Override        public boolean onScale(ScaleGestureDetector detector) {            int left = 0, right = 0, top = 0, bottom = 0;            float length = 0;            if (mode == MODE_ZOOM) {                float ratio = detector.getScaleFactor();                left = getLeft();                top = getTop();                bottom = getBottom();                right = getRight();                if (ratio > 1) { // 放大撞状态                    length = (int) ((getHeight() * (ratio - 1)) / 7.0);                    left = (int) (left - length / 2);                    right = (int) (right + length / 2);                    bottom = (int) (bottom + length / 2);                    top = (int) (top - length / 2);                    if (getWidth() <= (screenWidth * 3) && getHeight() <= (fatherView_H * 3)) {                        setPosition(left, top, right, bottom);                    }                } else {                    length = (int) ((getHeight() * (1 - ratio)) / 7.0);                    left = (int) (left + length / 2);                    right = (int) (right - length / 2);                    bottom = (int) (bottom - length / 2);                    top = (int) (top + length / 2);                    if (left >= 0) {                        left = 0;                    }                    if (right <= screenWidth) {                        right = screenWidth;                    }                    if (top >= 0) {                        top = 0;                    }                    if (bottom <= fatherView_H) {                        bottom = fatherView_H;                    }                    if (getWidth() > initViewWidth && getHeight() > fatherView_H) {                        setPosition(left, top, right, bottom);                    } else {                        setPosition(start_Left, start_Top, start_Right, start_Bottom);                    }                }            }            return false;        }        @Override        public boolean onScaleBegin(ScaleGestureDetector detector) {            return true;        }        @Override        public void onScaleEnd(ScaleGestureDetector detector) {        }    }    /**     * 双击事件的处理     *      * @author Administrator     *      */    private class simpleGestureListener extends GestureDetector.SimpleOnGestureListener {        // 用到的双击的方法        public boolean onDoubleTap(MotionEvent e) {            Log.i(TAG, "双击屏幕");            // 双击屏幕            int left = 0, top = 0, right = 0, bottom = 0;            int length = 0;            left = getLeft();            top = getTop();            bottom = getBottom();            right = getRight();            if (getHeight() > fatherView_H) {                // 缩小模式                Log.i(TAG, "缩小模式");                while (getHeight() > fatherView_H) {                    length = (int) ((getHeight() * ratio) / 5.0);                    left = (int) (getLeft() + length / 2);                    right = (int) (getRight() - length / 2);                    bottom = (int) (getBottom() - length / 2);                    top = (int) (getTop() + length / 2);                    if (left >= 0) {                        left = 0;                    }                    if (right <= screenWidth) {                        right = screenWidth;                    }                    if (top >= 0) {                        top = 0;                    }                    if (bottom <= fatherView_H) {                        bottom = fatherView_H;                    }                    if (getWidth() > initViewWidth && getHeight() > fatherView_H) {                        setPosition(left, top, right, bottom);                    } else {                        setPosition(start_Left, start_Top, start_Right, start_Bottom);                    }                    try {                        Thread.sleep(10);                    } catch (InterruptedException e1) {                        e1.printStackTrace();                    }                }            } else {                // 放大模式                Log.i(TAG, "放大模式");                if (getHeight() <= fatherView_H) {                    while (getHeight() < initViewHeight * 2) {                        length = (int) ((getHeight() * ratio) / 5.0);                        left = (int) (getLeft() - length / 2);                        right = (int) (getRight() + length / 2);                        bottom = (int) (getBottom() + length / 2);                        top = (int) (getTop() - length / 2);                        if (getWidth() <= (screenWidth * 3) && getHeight() <= (fatherView_H * 3)) {                            setPosition(left, top, right, bottom);                        }                        try {                            Thread.sleep(10);                        } catch (InterruptedException e1) {                            e1.printStackTrace();                        }                    }                }            }            return true;        }    }    /** 实现拖动的处理 */    private void setPosition(int left, int top, int right, int bottom) {        this.layout(left, top, right, bottom);    }    /**     * surfaceView父控件的宽高     *      * @param fatherView_Width     * @param fatherView_Height     */    public void setFatherW_H(int fatherView_Width, int fatherView_Height) {        this.fatherView_W = fatherView_Width;        this.fatherView_H = fatherView_Height;    }    public void setLayoutParam(float scale) {        LinearLayout.LayoutParams layoutParams = (LayoutParams) getLayoutParams();        layoutParams.gravity = Gravity.CENTER;        layoutParams.width = (int) (scale * (layoutParams.width));        layoutParams.height = (int) (scale * (layoutParams.height));        setLayoutParams(layoutParams);    }    /** 获取两点的距离 **/    private float getDistance(float distanceX, float distanceY) {        return FloatMath.sqrt(distanceX * distanceX + distanceY * distanceY);    }    public void setFatherTopAndBottom(int fatherTop, int fatherBottom) {        this.fatherTop = fatherTop;        this.fatherBottom = fatherBottom;    }     /**     * 一定一个接口     */    public interface ICoallBack {        void getAngle(int angle, int viewW);    }    /**     * 初始化接口变量     */    ICoallBack icallBack = null;    /**     * 自定义控件的自定义事件     */    public void setEvent(ICoallBack iBack) {        icallBack = iBack;    }}

仿360的那个小滑动条

package com.example.surfaceviewdemo;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.RectF;import android.util.AttributeSet;import android.util.DisplayMetrics;import android.util.Log;import android.view.View;public class CustomMonitorMenu extends View {    public final int R1 = 100;    public final int R2 = 8;    //每一格 cos y的差距    public float width;    public float height;    public float screenWidth;    public float screenHeight;    public int startAngle = 235;  //新的角度 开始时30    public float initialAngle = 0.1f;  //初始弧度30    public int sweepAngle = 70;  //角度    public double newX;    public double newY;   //给小圆球提供位置 空间移动到这个位置上面去    public Paint mPaint2;    public Paint mPaint3;    public Paint mPaint4;    public boolean flag = false;    public Paint mPaint;    public Context mContext;    public String Sangle = "0";    public String Eangle = "120";    /**     * 一定一个接口     */    public interface ICoallBack {        void getAngle(int angle);    }    /**     * 初始化接口变量     */    ICoallBack icallBack = null;    /**     * 自定义控件的自定义事件     */    public void setEvent(ICoallBack iBack) {        icallBack = iBack;    }    public CustomMonitorMenu(Context context) {        super(context);        this.mContext = context;        this.setLayerType(View.LAYER_TYPE_SOFTWARE, null);        initView();//      setWillNotDraw(false);    }    public CustomMonitorMenu(Context context, AttributeSet attrs) {        super(context, attrs);        this.mContext = context;        this.setLayerType(View.LAYER_TYPE_SOFTWARE, null);        initView();//      setWillNotDraw(false);    }    public void setindex(int initAng, int viewW) {        int viewX = (int) (viewW - screenWidth);        if (viewX != 0) {            initialAngle = Math.abs(initAng) * sweepAngle / viewX;        }else {            viewW = 1;        }        if (initialAngle >= 0 && initialAngle <= 70) {            initialAngle = 35 - initialAngle;        }        Log.e("hgz------->", " initAng = " + Math.abs(initAng) + " initialAngle = " + initialAngle + " viewX = " + viewX);        invalidate();    }    private void initView() {        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);        mPaint.setColor(Color.BLACK);        mPaint.setAntiAlias(true);        mPaint.setStrokeWidth(2.0f);        mPaint.setStyle(Paint.Style.STROKE);        mPaint2 = new Paint(Paint.ANTI_ALIAS_FLAG); // 抗锯齿        mPaint2.setColor(Color.BLACK);        mPaint2.setStrokeWidth(2.0f);        mPaint2.setStrokeJoin(Paint.Join.ROUND); // 让画的线圆滑        mPaint2.setStrokeCap(Paint.Cap.ROUND);        mPaint3 = new Paint();        mPaint3.setColor(Color.BLACK);        mPaint3.setStrokeWidth(2.0f);        mPaint3.setStyle(Paint.Style.STROKE);        mPaint3.setAntiAlias(true);        mPaint4 = new Paint(Paint.ANTI_ALIAS_FLAG);        mPaint4.setStrokeWidth(1);        mPaint4.setTextSize(16);        mPaint4.setStyle(Paint.Style.STROKE);        mPaint4.setColor(Color.BLACK);// 下面这行是实现水平居中,drawText对应改为传入targetRect.centerX()//      mPaint4.setTextAlign(Paint.Align.CENTER);//        根据屏幕的宽高确定圆心的坐标        DisplayMetrics metric = new DisplayMetrics();        ((MainActivity) mContext).getWindowManager().getDefaultDisplay().getMetrics(metric);//      屏幕的宽高        screenWidth = metric.widthPixels;        screenHeight = metric.heightPixels;//       圆心位置坐标        width = metric.widthPixels / 2.0f;        height = metric.heightPixels / 8.0f;        Log.e("aaa--->圆心的坐标:", width + "---" + height);    }    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        RectF oval1 = new RectF(width - 100, height - 100, width + 100, height + 100);        canvas.drawArc(oval1, startAngle, sweepAngle, false, mPaint);//小弧形        Log.e("ooo--->", "圆环的圆心的坐标 : width " + width + "   height " + height);//        getNewLocation(initialAngle); //根据判断 来移动小球 获得新的位置        canvas.drawLine(width, (height - R1), width, (height - R1) + 10, mPaint3);        canvas.drawText(Sangle, (float) (width - Math.sin(35 * Math.PI / 180) * R1) - 20, (float) (height - Math.cos(35 * Math.PI / 180) * R1) + 10, mPaint4);        canvas.drawText(Eangle, (float) (width + Math.sin(35 * Math.PI / 180) * R1) + 8, (float) (height - Math.cos(35 * Math.PI / 180) * R1) + 10, mPaint4);//        canvas.drawCircle((float) newX, (float) newY, R2, mPaint2);        canvas.drawLine((float) (width - Math.sin(35 * Math.PI / 180) * R1), (float) (height - Math.cos(35 * Math.PI / 180) * R1),                (float) (width - Math.sin(35 * Math.PI / 180) * R1) - 5.0f, (float) (height - Math.cos(35 * Math.PI / 180) * R1) - 6.0f, mPaint3);        canvas.drawLine((float) (width - Math.sin(35 * Math.PI / 180) * R1), (float) (height - Math.cos(35 * Math.PI / 180) * R1),                (float) (width - Math.sin(35 * Math.PI / 180) * R1) + 5.0f, (float) (height - Math.cos(35 * Math.PI / 180) * R1) + 6.0f, mPaint3);        canvas.drawLine((float) (width + Math.sin(35 * Math.PI / 180) * R1), (float) (height - Math.cos(35 * Math.PI / 180) * R1),                (float) (width + Math.sin(35 * Math.PI / 180) * R1) + 5.0f, (float) (height - Math.cos(35 * Math.PI / 180) * R1) - 6.0f, mPaint3);        canvas.drawLine((float) (width + Math.sin(35 * Math.PI / 180) * R1), (float) (height - Math.cos(35 * Math.PI / 180) * R1),                (float) (width + Math.sin(35 * Math.PI / 180) * R1) - 5.0f, (float) (height - Math.cos(35 * Math.PI / 180) * R1) + 6.0f, mPaint3);//        canvas.drawCircle((float) (width - Math.sin(35 * Math.PI / 180) * R1), (float) (height - Math.cos(35 * Math.PI / 180) * R1), R2, mPaint2);        canvas.drawCircle((float) (width - Math.sin(initialAngle * Math.PI / 180) * R1), (float) (height - Math.cos(initialAngle * Math.PI / 180) * R1), R2, mPaint2);        Log.e("hgz", "小球的坐标:" + (float) (width - Math.sin(initialAngle * Math.PI / 180) * R1) + "     " + (float) (height - Math.cos(initialAngle * Math.PI / 180) * R1));//        canvas.drawCircle((float) (width + Math.sin(35 * Math.PI / 180) * R1), (float) (height - Math.cos(35 * Math.PI / 180) * R1), R2, mPaint2);    }}

ScreenUtils尺寸工具类

package com.example.surfaceviewdemo;import android.app.Activity;import android.content.Context;import android.graphics.Bitmap;import android.graphics.Rect;import android.util.DisplayMetrics;import android.view.View;import android.view.WindowManager;public class ScreenUtils {     private ScreenUtils()          {              /* cannot be instantiated */              throw new UnsupportedOperationException("cannot be instantiated");          }          /**          * 获得屏幕高度          *           * @param context          * @return          */          public static int getScreenWidth(Context context)          {              WindowManager wm = (WindowManager) context                      .getSystemService(Context.WINDOW_SERVICE);              DisplayMetrics outMetrics = new DisplayMetrics();              wm.getDefaultDisplay().getMetrics(outMetrics);              return outMetrics.widthPixels;          }          /**          * 获得屏幕宽度          *           * @param context          * @return          */          public static int getScreenHeight(Context context)          {              WindowManager wm = (WindowManager) context                      .getSystemService(Context.WINDOW_SERVICE);              DisplayMetrics outMetrics = new DisplayMetrics();              wm.getDefaultDisplay().getMetrics(outMetrics);              return outMetrics.heightPixels;          }          /**          * 获得状态栏的高度          *           * @param context          * @return          */          public static int getStatusHeight(Context context)          {              int statusHeight = -1;              try              {                  Class<?> clazz = Class.forName("com.android.internal.R$dimen");                  Object object = clazz.newInstance();                  int height = Integer.parseInt(clazz.getField("status_bar_height")                          .get(object).toString());                  statusHeight = context.getResources().getDimensionPixelSize(height);              } catch (Exception e)              {                  e.printStackTrace();              }              return statusHeight;          }          /**          * 获取当前屏幕截图,包含状态栏          *           * @param activity          * @return          */          public static Bitmap snapShotWithStatusBar(Activity activity)          {              View view = activity.getWindow().getDecorView();              view.setDrawingCacheEnabled(true);              view.buildDrawingCache();              Bitmap bmp = view.getDrawingCache();              int width = getScreenWidth(activity);              int height = getScreenHeight(activity);              Bitmap bp = null;              bp = Bitmap.createBitmap(bmp, 0, 0, width, height);              view.destroyDrawingCache();              return bp;          }          /**          * 获取当前屏幕截图,不包含状态栏          *           * @param activity          * @return          */          public static Bitmap snapShotWithoutStatusBar(Activity activity)          {              View view = activity.getWindow().getDecorView();              view.setDrawingCacheEnabled(true);              view.buildDrawingCache();              Bitmap bmp = view.getDrawingCache();              Rect frame = new Rect();              activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);              int statusBarHeight = frame.top;              int width = getScreenWidth(activity);              int height = getScreenHeight(activity);              Bitmap bp = null;              bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height                      - statusBarHeight);              view.destroyDrawingCache();              return bp;          }  }

主Activity

package com.example.surfaceviewdemo;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class SplashActivity extends Activity{    Button btnstartPortActivity;    Button btnstartLandActivity;    @Override    protected void onCreate(Bundle savedInstanceState) {        // TODO Auto-generated method stub        super.onCreate(savedInstanceState);        setContentView(R.layout.splash_layout);        btnstartLandActivity = (Button) findViewById(R.id.start_landscape_activity);        btnstartPortActivity = (Button) findViewById(R.id.start_portable_activity);        btnstartPortActivity.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                Intent intent = new Intent(SplashActivity.this,MainActivity.class);                startActivity(intent);            }        });        btnstartLandActivity.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                Intent intent = new Intent(SplashActivity.this,DemoActivty.class);                startActivity(intent);            }        });    }}

纵屏播放Activity

package com.example.surfaceviewdemo;import java.io.IOException;import android.app.Activity;import android.content.res.AssetFileDescriptor;import android.media.AudioManager;import android.media.MediaPlayer;import android.os.Bundle;import android.util.Log;import android.view.Gravity;import android.view.Menu;import android.view.SurfaceHolder;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.LinearLayout;import android.widget.LinearLayout.LayoutParams;import com.example.surfaceviewdemo.CustomSurfaceView.ICoallBack;public class MainActivity extends Activity {    public static final String TAG = "MyGesture";    Button btn_start;    Button btn_end;    CustomSurfaceView customSurfaceView;    private SurfaceHolder surfaceHolder;    private MediaPlayer mediaPlayer;    String pathVideo;    LinearLayout line_view;    private int fatherView_W;    private int fatherView_H;    CustomMonitorMenu customMonitorMenu;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        btn_start = (Button) findViewById(R.id.start_vedio);        btn_end = (Button) findViewById(R.id.stop_vedio);        line_view = (LinearLayout) findViewById(R.id.line_view);        customSurfaceView = (CustomSurfaceView) findViewById(R.id.hv_scrollView);        LayoutParams layoutParams = (LayoutParams) customSurfaceView.getLayoutParams();        layoutParams.width = (int) (ScreenUtils.getScreenWidth(getApplicationContext()) * (1.2));        layoutParams.gravity = Gravity.CENTER;        customMonitorMenu = (CustomMonitorMenu) findViewById(R.id.custom_Menu);        customSurfaceView.setLayoutParams(layoutParams);        initgetViewW_H();        btn_start.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                playSurfaceView();            }        });        btn_end.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                stopSurfaceView();            }        });        surfaceHolder = customSurfaceView.getHolder();        surfaceHolder.setFixedSize(800, 800);        surfaceHolder.setKeepScreenOn(true);        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);        surfaceHolder.addCallback(new SurfaceHolder.Callback() {            @Override            public void surfaceCreated(SurfaceHolder holder) {            }            @Override            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {            }            @Override            public void surfaceDestroyed(SurfaceHolder holder) {                if (mediaPlayer != null && mediaPlayer.isPlaying()) {                    mediaPlayer.stop();                }            }        });        customSurfaceView.setEvent(new ICoallBack() {            @Override            public void getAngle(int angle, int viewW) {                if (customMonitorMenu != null) {                    customMonitorMenu.setindex(angle, viewW);                }            }        });    }    private void initgetViewW_H() {        line_view.postDelayed(new Runnable() {            @Override            public void run() {                fatherView_W = line_view.getWidth();                fatherView_H = line_view.getHeight();                Log.i(TAG, "father Top" + line_view.getTop());                Log.i(TAG, "father Bottom" + line_view.getBottom());                customSurfaceView.setFatherW_H(line_view.getTop(), line_view.getBottom());                customSurfaceView.setFatherTopAndBottom(line_view.getTop(), line_view.getBottom());            }        }, 100);    }    // 鏆傚仠    public void stopSurfaceView() {        if (mediaPlayer != null && mediaPlayer.isPlaying()) {            mediaPlayer.stop();            mediaPlayer.release();            mediaPlayer = null;        }    }    // 寮�濮嬫挱鏀捐棰�    public void playSurfaceView() {        try {            if (mediaPlayer == null) {                mediaPlayer = new MediaPlayer();            }            mediaPlayer.reset();            AssetFileDescriptor in = getResources().getAssets().openFd("hgz.mp4");            mediaPlayer.setDataSource(in.getFileDescriptor(), in.getStartOffset(), in.getLength());            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);            mediaPlayer.setDisplay(surfaceHolder);            mediaPlayer.prepare();            mediaPlayer.start();        } catch (IOException e) {            e.printStackTrace();        }    }    @Override    protected void onDestroy() {        super.onDestroy();        if (mediaPlayer != null && mediaPlayer.isPlaying()) {            mediaPlayer.stop();            mediaPlayer.release();            mediaPlayer = null;        }    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        getMenuInflater().inflate(R.menu.main, menu);        return true;    }}

横屏幕播放Activity

package com.example.surfaceviewdemo;import java.io.IOException;import android.app.Activity;import android.content.res.AssetFileDescriptor;import android.media.AudioManager;import android.media.MediaPlayer;import android.os.Bundle;import android.util.Log;import android.view.Gravity;import android.view.Menu;import android.view.SurfaceHolder;import android.view.View;import android.view.View.OnClickListener;import android.widget.BaseAdapter;import android.widget.Button;import android.widget.LinearLayout;import android.widget.LinearLayout.LayoutParams;public class DemoActivty extends Activity {    public static final String TAG = "MyGesture";    Button btn_start;    Button btn_end;    CustomSurfaceView customSurfaceView;    private SurfaceHolder surfaceHolder;    private MediaPlayer mediaPlayer;    String pathVideo;    LinearLayout line_view;    private int fatherView_W;    private int fatherView_H;    @Override    protected void onCreate(Bundle savedInstanceState) {        // TODO Auto-generated method stub        super.onCreate(savedInstanceState);        setContentView(R.layout.demo_layout);        btn_start = (Button) findViewById(R.id.start_vedio);        btn_end = (Button) findViewById(R.id.stop_vedio);        line_view = (LinearLayout) findViewById(R.id.line_view);        customSurfaceView = (CustomSurfaceView) findViewById(R.id.hv_scrollView);        LayoutParams layoutParams = (LayoutParams) customSurfaceView.getLayoutParams();        layoutParams.gravity = Gravity.CENTER;        customSurfaceView.setLayoutParams(layoutParams);        initgetViewW_H();        btn_start.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                playSurfaceView();            }        });        btn_end.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                stopSurfaceView();            }        });        surfaceHolder = customSurfaceView.getHolder();        surfaceHolder.setFixedSize(800, 800);        surfaceHolder.setKeepScreenOn(true);        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);        surfaceHolder.addCallback(new SurfaceHolder.Callback() {            @Override            public void surfaceCreated(SurfaceHolder holder) {            }            @Override            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {            }            @Override            public void surfaceDestroyed(SurfaceHolder holder) {                if (mediaPlayer != null && mediaPlayer.isPlaying()) {                    mediaPlayer.stop();                }            }        });    }    private void initgetViewW_H() {        line_view.postDelayed(new Runnable() {            @Override            public void run() {                fatherView_W = line_view.getWidth();                fatherView_H = line_view.getHeight();                Log.i(TAG, "father Top" + line_view.getTop());                Log.i(TAG, "father Bottom" + line_view.getBottom());                customSurfaceView.setFatherW_H(line_view.getTop(), line_view.getBottom());                customSurfaceView.setFatherTopAndBottom(line_view.getTop(), line_view.getBottom());            }        }, 100);    }    // 鏆傚仠    public void stopSurfaceView() {        if (mediaPlayer != null && mediaPlayer.isPlaying()) {            mediaPlayer.stop();            mediaPlayer.release();            mediaPlayer = null;        }    }    // 寮�濮嬫挱鏀捐棰�    public void playSurfaceView() {        try {            if (mediaPlayer == null) {                mediaPlayer = new MediaPlayer();            }            mediaPlayer.reset();            AssetFileDescriptor in = getResources().getAssets().openFd("hgz.mp4");            mediaPlayer.setDataSource(in.getFileDescriptor(), in.getStartOffset(), in.getLength());            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);            mediaPlayer.setDisplay(surfaceHolder);            mediaPlayer.prepare();            mediaPlayer.start();        } catch (IOException e) {            e.printStackTrace();        }    }    @Override    protected void onDestroy() {        super.onDestroy();        if (mediaPlayer != null && mediaPlayer.isPlaying()) {            mediaPlayer.stop();            mediaPlayer.release();            mediaPlayer = null;        }    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        getMenuInflater().inflate(R.menu.main, menu);        return true;    }}

因为这个代码写了已经有八九个月了,之前很多东西都是总结在有道云笔记当中,这段时间把它转移到Csdn上来,所以才把它拿出来,可能也有些写的不好,希望吧 能给大家一点帮助,源代码是可以直接run的,

源代码地址:源码地址

如果有什么疑问的或者缺陷的地方也可以及时联系作者

谢谢大家的观看

0 0
原创粉丝点击