Play video by texture with video aspect ratio

I play video from my server on the surface using a texture view, but its stretching the video and the inability to maintain the aspect ratio of the video. But I want to maintain the aspect ratio according to the video, as in the wine app or instagram app.

+6
source share
4 answers

You can either resize the view (using its own FrameLayout) or use the TextureView matrix to change the way the texture is displayed.

Examples of both can be found at Grafika . The β€œPlay Video (TextureView)” activity shows the matrix setting according to the aspect ratio of the video. See the adjustAspectRatio() Method, the core of which is:

  Matrix txform = new Matrix(); mTextureView.getTransform(txform); txform.setScale((float) newWidth / viewWidth, (float) newHeight / viewHeight); txform.postTranslate(xoff, yoff); mTextureView.setTransform(txform); 

Note that it centers and also scales the video.

+10
source

You can use ExoPlayer https://github.com/google/ExoPlayer# and check out the full demo. It perfectly supports the aspect ratio of the video.

+1
source

Turning around the answer above: If you want to align the video in a different way, and not just center it, change these lines in Grafika's code "adjustAspectRatio ()":

 int xoff = (viewWidth - newWidth) / 2; int yoff = (viewHeight - newHeight) / 2; 

in

 int xoff = 0; //align left 

or

 int xoff = (viewWidth - newWidth); // align right 

or

 int yoff = 0; // align top 

or

 int yoff = (viewHeight - newHeight); // align bottom 
0
source

Well, I'm too late to answer, but since I received from Grafika , you can use this function

  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); } 
0
source

Source: https://habr.com/ru/post/979442/


All Articles