在SurfaceView的onMeasure()中,如何计算当前视图的大小

时间:2014-05-12 11:48:17

标签: android android-mediaplayer

在我的Android视频播放器中,如何设置视频大小,使其适合视图。

我创建了一个CustomView extends SurfaceView。在覆盖onMeasure()中,我正在考虑计算我的CustomView(显示视频)的大小。

然后在setMeasuredDimension(width, height);中传递这些维度。

我没有遇到任何其他手动设置视频尺寸的方法。

由于

1 个答案:

答案 0 :(得分:0)

完美示例here,或者看看,

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

int desiredWidth = 100;
int desiredHeight = 100;

int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);

int width;
int height;

//Measure Width
if (widthMode == MeasureSpec.EXACTLY) {
    //Must be this size
    width = widthSize;
} else if (widthMode == MeasureSpec.AT_MOST) {
    //Can't be bigger than...
    width = Math.min(desiredWidth, widthSize);
} else {
    //Be whatever you want
    width = desiredWidth;
}

//Measure Height
if (heightMode == MeasureSpec.EXACTLY) {
    //Must be this size
    height = heightSize;
} else if (heightMode == MeasureSpec.AT_MOST) {
    //Can't be bigger than...
    height = Math.min(desiredHeight, heightSize);
} else {
    //Be whatever you want
    height = desiredHeight;
}

//MUST CALL THIS
setMeasuredDimension(width, height);
}

希望得到它的帮助。