计算视频比例:
(这种方法不灵活,需要在有误差值时主动进位,计算在误差范围内它是属于哪种比例视频)
例:假设读取到视频宽高为:宽720(videoWidth) 高1280(videoHeight) 现在我不知道它是哪个比例;那我们先列出常用比例:16:9、4:3、1:1、9:16、3:4、5:8、2:1、1.85:1
宽>高的,那是‘横向长方形’视频!有:16:9、4:3、2:1、1.85:1
高>宽的,那是‘竖向长方形’视频!有:9:16、3:4、5:8
if (videoHeight == videoWidth) { // 正方形 return }
if (videoHeight > videoWidth) {
// 竖向长方形
if (videoHeight * 9 == videoWidth * 16 ) { // 高宽比:9:16 return }
if (videoHeight * 3 == videoWidth * 4) { // 高宽比:3:4 return }
if (videoHeight * 5 == videoWidth * 8) { // 高宽比:5:8 return }
}
if (videoWidth > videoHeight) {
// 横向长方形
if (videoHeight * 16 == videoWidth * 9) { // 高宽比:16:9 return }
if (videoHeight * 4 == videoWidth * 3) { // 高宽比:4:3 return }
if ((videoHeight * 1.85).toInt() == videoWidth * 1) { // 高宽比:1.85:1 return }
}
动态设置视频尺寸:
取屏幕宽
val screenWidth = mContext.resources.displayMetrics.widthPixels
var params = FrameLayout.LayoutParams(mScreenWidth , ViewGroup.LayoutParams.WRAP_CONTENT , Gravity.CENTER)
if (mItem.videoHeight == mItem.videoWidth) { // 正方形
// LayoutParams 其中的成员width和height都以px为单位
params = FrameLayout.LayoutParams(mScreenWidth , mScreenWidth , Gravity.CENTER)
}
if (mItem.videoHeight > mItem.videoWidth) {// 竖向长方形
// 计算高度
// 1.计算宽高倍数
val b1 = BigDecimal(mItem.videoHeight)
val b2 = BigDecimal(mItem.videoWidth)
// 2.得出高是宽的几倍,结果为大于1的数
var b3 = b1.divide(b2 , 2 , BigDecimal.ROUND_DOWN).toFloat()
// 3.得出高度 ,屏宽*倍数
LogUtils.iYx("----竖向长方形----${b3.toInt()}")
// LayoutParams 其中的成员width和height都以px为单位
params = FrameLayout.LayoutParams(mScreenWidth , b3.toInt() , Gravity.CENTER)
}
if (mItem.videoWidth > mItem.videoHeight) { // 横向长方形
// 计算高度
// 1.计算宽高倍数
val b1 = BigDecimal(mItem.videoHeight)
val b2 = BigDecimal(mItem.videoWidth)
// 2.得出高是宽的几倍,结果为小于1的数
val b3 = b1.divide(b2 , 2 , BigDecimal.ROUND_DOWN).toFloat()
// 3.宽度必须充满屏幕,则有可能Item宽度需要增加:结果为w
val w = mScreenWidth - mItem.videoWidth
// 4.用新增的宽度w乘以倍数则等于Item高度需要增加的数值
val h = w * b3
// 5.得出高度
val itemH = mItem.videoHeight + h
LogUtils.iYx("----横向长方形----$itemH")
// sw1080 / 854/480 : 0.56 226 126.56 1080/606.56
// LayoutParams 其中的成员width和height都以px为单位
params = FrameLayout.LayoutParams(mScreenWidth , itemH.toInt() , Gravity.CENTER)
}
// 设置VideoView布局尺寸
containerView.mVideoView.layoutParams = params