短視頻程序源碼屏幕旋轉時改變SurfaceView(視頻)寬高

int mWidth = getMeasuredWidth();
int mHeight = getMeasuredHeight();
int oldAngle = 90;

/**
 * 旋轉更新(屏幕旋轉時調用,0和180 -> 橫屏,90和270 -> 豎屏)
 * 屏幕旋轉需要考慮旋轉後的高寬變化,例如:豎屏時,高比寬大,橫屏時:高比寬小。
 * 所以旋轉後要確定那邊爲寬,那邊爲高,然後將視頻等比例縮放至屏幕相應大小。
 * @param angle     旋轉角度。傳入0、180、90、270
 */
private void updateOrientation(int angle) {
    if( videoWidth <= 0 || videoHeight <= 0 ) return;
    //需要改變寬高的LayoutParams
    ViewGroup.LayoutParams lp = getLayoutParams();
    //是否爲橫版視頻
    boolean isLandscapeVideo = videoWidth > videoHeight;
    //是否爲橫屏
    boolean isLandscapeScreen = angle == 0 || angle == 180;
    /* 因爲橫豎屏原因,高寬會發生改變,所以需要取最值來判斷高寬 */
    int max = mWidth < mHeight ? mHeight : mWidth;
    int min = mWidth > mHeight ? mHeight : mWidth;

    //-1爲平放狀態
    if( angle == -1 ) angle = oldAngle;

    /* 屏幕旋轉一共四種結果:豎屏橫視頻、豎屏豎視頻、橫屏橫視頻、橫屏豎視頻
     * 其次,這是經過一段很長的代碼精簡而來,請不要嘗試去理解這些代碼。
     * 大概意思是橫豎屏時判斷當前視頻的橫豎,對高寬進行等比縮放 */
    if( (isLandscapeVideo && isLandscapeScreen) || (!isLandscapeVideo && !isLandscapeScreen) ) {
        /* 橫屏橫視頻 和 豎屏豎視頻 */
        lp.width = Utils.calcAspectRatio(
                videoWidth, videoHeight, isLandscapeScreen ? min : max, false
        );
        if( lp.width > ( isLandscapeScreen ? max : min ) ) {
            lp.height = Utils.calcAspectRatio(
                    videoWidth, videoHeight, isLandscapeScreen ? max : min, true
            );
            lp.width = isLandscapeScreen ? max : min;
        }else {
            lp.height = isLandscapeScreen ? min : max;
        }
    }else {
        /* 豎屏橫視頻 和 橫屏豎視頻 */
        lp.width = min + Utils.calcAspectRatio(videoHeight, videoWidth, min, isLandscapeScreen);
        lp.height = isLandscapeScreen ? min : lp.width - min;
        lp.width = isLandscapeScreen ? lp.width - min : min;
    }
    setLayoutParams( lp );

    if( angle != -1 ) oldAngle = angle;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章