#videoView控件全屏等比例显示
经常遇到不同尺寸的视频,采用MediaPlayer播放我感觉没有videoView方便,因为MediaPlayer需要依赖另一个控件用于显示视频,但是MediaPlayer全屏铺满有自带的方法it.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING)
,但是VideoView没有这种方法,需要自己根据视频尺寸处理
###自定义继承VideoView
open class FullScreenVideoView : VideoView {
private var widthX: Int? = 0
private var heightX: Int? = 0
constructor(context: Context?) : super(context) {}
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {}
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context,
attrs,
defStyleAttr) {
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
if (widthX == 0) {
val width = getDefaultSize(0, widthMeasureSpec)
val height = getDefaultSize(0, heightMeasureSpec)
setMeasuredDimension(width, height)
} else {
var width = getDefaultSize(0, widthMeasureSpec)
var height = getDefaultSize(0, heightMeasureSpec)
if (widthX == heightX) {
setMeasuredDimension(width, height)
}
if (heightX!! > widthX!! && width > widthX!!) {
height = width * heightX!! / widthX!!
} else if (widthX!! > heightX!! && height > heightX!!) {
width = height * widthX!! / heightX!!
} else if (heightX!! > widthX!! && widthX!! > width) {
height = width!! * heightX!! / widthX!!
} else if (widthX!! > heightX!! && heightX!! > height) {
width = height * widthX!! / heightX!!
}
setMeasuredDimension(width, height)
}
}
open fun setSizeX(widthSize: Int, heightSize: Int) {
widthX = widthSize
heightX = heightSize
postInvalidate()
}
}
###xml文件中引用,相对布局居中显示,实现视频由中间向外缩放显示
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:gravity="center"
tools:context=".ui.activity.MainActivity">
<你的包名ui.view.FullScreenVideoView
android:id="@+id/v_video"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
###avtivity中引用播放视频资源
val uri: Uri = Uri.parse(filePath)
binding.vVideo.setVideoURI(uri)
binding.vVideo.setOnPreparedListener {
//获取视频的尺寸
binding.vVideo.setSizeX(it.videoWidth,it.videoHeight)
}
binding.vVideo.start()
binding.vVideo.requestFocus()
binding.vVideo.setOnCompletionListener(MediaPlayer.OnCompletionListener { mPlayer ->
mPlayer.start()
mPlayer.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING)
mPlayer.isLooping = true
})
binding.vVideo.setOnErrorListener(MediaPlayer.OnErrorListener { mp, what, extra ->
println("aaa onError: vod play error.")
binding.vVideo.stopPlayback()//播放异常,则停止播放,防止弹窗使界面阻塞
true
})