override fun onMeasure()

in PictureInPictureKotlin/app/src/main/java/com/example/android/pictureinpicture/widget/MovieView.kt [181:221]


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        mediaPlayer?.let { player ->
            val videoWidth = player.videoWidth
            val videoHeight = player.videoHeight
            if (videoWidth != 0 && videoHeight != 0) {
                val aspectRatio = videoHeight.toFloat() / videoWidth
                val width = MeasureSpec.getSize(widthMeasureSpec)
                val widthMode = MeasureSpec.getMode(widthMeasureSpec)
                val height = MeasureSpec.getSize(heightMeasureSpec)
                val heightMode = MeasureSpec.getMode(heightMeasureSpec)
                if (adjustViewBounds) {
                    if (widthMode == MeasureSpec.EXACTLY
                            && heightMode != MeasureSpec.EXACTLY) {
                        super.onMeasure(widthMeasureSpec,
                                MeasureSpec.makeMeasureSpec((width * aspectRatio).toInt(),
                                        MeasureSpec.EXACTLY))
                    } else if (widthMode != MeasureSpec.EXACTLY
                            && heightMode == MeasureSpec.EXACTLY) {
                        super.onMeasure(MeasureSpec.makeMeasureSpec((height / aspectRatio).toInt(),
                                MeasureSpec.EXACTLY), heightMeasureSpec)
                    } else {
                        super.onMeasure(widthMeasureSpec,
                                MeasureSpec.makeMeasureSpec((width * aspectRatio).toInt(),
                                        MeasureSpec.EXACTLY))
                    }
                } else {
                    val viewRatio = height.toFloat() / width
                    if (aspectRatio > viewRatio) {
                        val padding = ((width - height / aspectRatio) / 2).toInt()
                        setPadding(padding, 0, padding, 0)
                    } else {
                        val padding = ((height - width * aspectRatio) / 2).toInt()
                        setPadding(0, padding, 0, padding)
                    }
                    super.onMeasure(widthMeasureSpec, heightMeasureSpec)
                }
                return
            }
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }