我有一个正在显示视频的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);
}
试图使用它,但我只看到黑色背景。
这是关于SurfaceTextureAvailable的mu,如果它有帮助:
@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();
}
}
该方法有什么问题?如何保持纵横比?感谢。