我有一个 TextureView,其中显示了一个视频,一个以前用设备相机录制的视频。视频中的图像被拉伸,这是不可接受的。我做了一些研究,发现了这个方法:
private void adjustAspectRatio(int videoWidth, int videoHeight) {
int viewWidth = m_TextureView.getWidth();
int viewHeight = m_TextureView.getHeight();
double aspectRatio = (double) videoHeight / videoWidth;
int newWidth, newHeight;
if (viewHeight > (int) (viewWidth * aspectRatio)) {
// limited by narrow width; restrict height
newWidth = viewWidth;
newHeight = (int) (viewWidth * aspectRatio);
} else {
// limited by short height; restrict width
newWidth = (int) (viewHeight / aspectRatio);
newHeight = viewHeight;
}
int xoff = (viewWidth - newWidth) / 2;
int yoff = (viewHeight - newHeight) / 2;
Log.v(TAG, "video=" + videoWidth + "x" + videoHeight +
" view=" + viewWidth + "x" + viewHeight +
" newView=" + newWidth + "x" + newHeight +
" off=" + xoff + "," + yoff);
Matrix txform = new Matrix();
m_TextureView.getTransform(txform);
txform.setScale((float) newWidth / viewWidth, (float) newHeight / viewHeight);
//txform.postRotate(10); // just for fun
txform.postTranslate(xoff, yoff);
m_TextureView.setTransform(txform);
}
尝试使用它,但我只看到黑色背景。
这是 mu onSurfaceTextureAvailable,以防万一:
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
isVideoResultReady=true;
Surface s=new Surface(surface);
if(mPlayer==null){
mPlayer=new MediaPlayer();
}
try {
//mPlayer.setDataSource(videoPath);
mPlayer.setSurface(s);
mPlayer.prepare();
mPlayer.setOnBufferingUpdateListener(this);
mPlayer.setOnCompletionListener(this);
mPlayer.setOnPreparedListener(this);
//media player is started in other point of the app
} catch (IOException e) {
e.printStackTrace();
}
}
这种方法有什么问题?如何保持纵横比?谢谢。