Created
June 7, 2022 10:32
-
-
Save DenisShov/833cad7555bd18edb58fb5cfa8f60d67 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MeasuredVideoView @JvmOverloads constructor( | |
context: Context, | |
attrs: AttributeSet? = null, | |
defStyleAttr: Int = 0 | |
) : VideoView(context, attrs, defStyleAttr) { | |
private var videoWidth = 0 | |
private var videoHeight = 0 | |
init { | |
context.withStyledAttributes(attrs, R.styleable.MeasuredVideoView, 0, 0) { | |
setZOrderOnTop(getBoolean(R.styleable.MeasuredVideoView_zOrderOnTop, false)) | |
setVideoFile(getResourceId(R.styleable.MeasuredVideoView_videoFileRes, 0)) | |
} | |
} | |
fun setVideoFile(@RawRes fileName: Int) { | |
val filePath = "android.resource://" + context.packageName + "/" + fileName | |
calculateWidthAndHeight(filePath) | |
setVideoPath(filePath) | |
} | |
private fun calculateWidthAndHeight(filPath: String) { | |
val retriever = MediaMetadataRetriever() | |
retriever.setDataSource(this.context, Uri.parse(filPath)) | |
videoWidth = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)?.toInt() ?: 0 | |
videoHeight = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)?.toInt() ?: 0 | |
} | |
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { | |
var width = MeasureSpec.getSize(widthMeasureSpec) | |
var height = MeasureSpec.getSize(heightMeasureSpec) | |
if (videoWidth > 0 && videoHeight > 0) { | |
if (videoWidth * height > width * videoHeight) { | |
height = width * videoHeight / videoWidth | |
} else if (videoWidth * height < width * videoHeight) { | |
width = height * videoWidth / videoHeight | |
} | |
} | |
setMeasuredDimension(width, height) | |
} | |
} | |
<declare-styleable name="MeasuredVideoView"> | |
<attr name="zOrderOnTop" format="boolean"/> | |
<attr name="videoFileRes" format="reference"/> | |
</declare-styleable> | |
<com.coloplast.cathnow.ui.widgets.MeasuredVideoView | |
android:id="@+id/mvVideo" | |
android:layout_width="0dp" | |
android:layout_height="wrap_content" | |
android:layout_marginTop="88dp" | |
android:background="@color/intro_videos_background" | |
app:layout_constraintEnd_toEndOf="parent" | |
app:layout_constraintStart_toStartOf="parent" | |
app:layout_constraintTop_toTopOf="parent" | |
app:videoFileRes="@raw/animation_step_two" | |
app:zOrderOnTop="true" /> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment