【发布时间】:2015-02-09 15:53:02
【问题描述】:
我正在使用纹理视图在表面上播放来自服务器的视频,但它会拉伸视频并且无法保持视频的纵横比。但是,我希望像在 vine 应用程序或 instagram 应用程序中一样保持视频的纵横比。
【问题讨论】:
标签: android textureview
我正在使用纹理视图在表面上播放来自服务器的视频,但它会拉伸视频并且无法保持视频的纵横比。但是,我希望像在 vine 应用程序或 instagram 应用程序中一样保持视频的纵横比。
【问题讨论】:
标签: android textureview
您可以更改 View 的大小(使用自定义 FrameLayout),或使用 TextureView 矩阵更改纹理的渲染方式。
两者的示例都可以在Grafika 中找到。 “播放视频(TextureView)”活动演示了配置矩阵以匹配视频的纵横比。见adjustAspectRatio()方法,其核心是:
Matrix txform = new Matrix();
mTextureView.getTransform(txform);
txform.setScale((float) newWidth / viewWidth, (float) newHeight / viewHeight);
txform.postTranslate(xoff, yoff);
mTextureView.setTransform(txform);
注意它会居中以及缩放视频。
【讨论】:
好吧,我来不及回答了,但正如我从 Grafika 那里得到的那样,您可以使用此功能
private void adjustAspectRatio(int videoWidth, int videoHeight) {
int viewWidth = mTextureView.getWidth();
int viewHeight = mTextureView.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();
mTextureView.getTransform(txform);
txform.setScale((float) newWidth / viewWidth, (float) newHeight / viewHeight);
//txform.postRotate(10); // just for fun
txform.postTranslate(xoff, yoff);
mTextureView.setTransform(txform);
}
【讨论】:
FILL resize 时垂直拉伸,我想填充并居中裁剪
您可以使用 ExoPlayer https://github.com/google/ExoPlayer# 并查看完整演示。它完美地保持了视频的纵横比。
【讨论】:
扩展上面fadden的答案: 如果您想以其他方式对齐视频,而不仅仅是居中, 在 Grafika 的“adjustAspectRatio()”代码中修改这些行:
int xoff = (viewWidth - newWidth) / 2;
int yoff = (viewHeight - newHeight) / 2;
到:
int xoff = 0; //align left
或
int xoff = (viewWidth - newWidth); // align right
或
int yoff = 0; // align top
或
int yoff = (viewHeight - newHeight); // align bottom
【讨论】: