CenterCrop的核心是使用TextureView的setTransform方法來(lái)實(shí)現(xiàn)對(duì)視頻區(qū)域的變換一死。
思路來(lái)自于:github
因?yàn)楫a(chǎn)品需求的原因棵红,在展示視頻的時(shí)候需要使用類(lèi)似ImageView的CenterCrop屬性噪舀。對(duì)指定區(qū)域進(jìn)行填充松蒜,對(duì)視頻等比放大擂涛。
重寫(xiě)了TextureView读串,在其中使用MediaPlayer來(lái)播放視頻。(上面庫(kù)的ScalableVideoView 類(lèi)里面)
我的實(shí)現(xiàn)是在重寫(xiě)TextureView的View的onMeasure方法里面進(jìn)行如下計(jì)算撒妈,來(lái)實(shí)現(xiàn)centerCrop:
int viewWidth = getDefaultSize(mVideoWidth, widthMeasureSpec);
int viewHeight = getDefaultSize(mVideoHeight, heightMeasureSpec);
setMeasuredDimension(viewWidth, viewHeight);
float scaleX = viewWidth * 1.0f / mVideoWidth;
float scaleY = viewHeight * 1.0f / mVideoHeight;
float maxScale = Math.max(scaleX, scaleY);
//中心位置
int pivotPointX = viewWidth / 2;
int pivotPointY = viewHeight / 2;
//初始效果是填滿(mǎn)View恢暖,相當(dāng)于fitXY. 這里從fitXY變成centerCrop..
mMatrix.setScale(maxScale / scaleX , maxScale / scaleY, pivotPointX, pivotPointY);
setTransform(mMatrix);