如何在自定义界面播放视频

时间:2019-04-29 21:09:14

标签: java android video kotlin surfaceview

有两个视频:行李和扫描的行李:

Two videos

任务是要显示两个视频,同时将它们与触摸屏幕周围可移动的圆圈区域重叠:

Result expected

我看到两种解决方法: Ways to solve

方法1:将X射线视频放到底部,在其下方放置原始视频并剪切圆圈区域。

方法2:在底部播放原始视频,创建圆形表面,并在该表面播放X射线视频

我选择了Way1。对于视频1,将SurfaceView与线程一起使用来处理画布。使用constraintLayout将视频2(X-Ray)定位在SurfaceView下:

class CircleSurfaceView(context: Context, attrs: AttributeSet) : SurfaceView(context, attrs), SurfaceHolder.Callback {
    private val drawThread by lazy { DrawThread(holder, resources,context) }
    private val player     by lazy { MediaPlayer.create(context, R.raw.dl_transhealthytolipid) }

    init {
        holder.addCallback(this)
    }

    override fun surfaceCreated(holder: SurfaceHolder?) {
        drawThread.setRunning(true)
        drawThread.start()
        player.setDisplay(holder)
        player.isLooping=true
        player.start()
        this.setBackgroundColor(Color.TRANSPARENT)
    }
    override fun surfaceChanged(holder: SurfaceHolder?, format: Int, width: Int, height: Int) {
    }
    override fun surfaceDestroyed(holder: SurfaceHolder?) {
        var isProcessing = true
        drawThread.setRunning(false)
        while (isProcessing) {
            try {
                drawThread.join()
                isProcessing = false
            } catch (e: InterruptedException) {
            }
        }
    }
}

画布剪切线程:

internal class DrawThread(private val surfaceHolder: SurfaceHolder, resources: Resources,context: Context) : Thread() {
    private var isProcessing = false
    private var previousTime: Long = 0

    fun setRunning(run: Boolean) {
        isProcessing = run
    }

    override fun run() {
        var canvas: Canvas?
        while (isProcessing) {
            // Perform the clipping every 30 mS
            val now = System.currentTimeMillis()
            val elapsedTime = now - previousTime
            if (elapsedTime > 30) {
                previousTime = now
            }
            synchronized(surfaceHolder) {
                canvas = surfaceHolder.lockCanvas(null)
                val clipPath=Path()
                //to simplify clipped fixed coordinates circle
                clipPath.addCircle(100f,100f,300f,Path.Direction.CW)
                canvas!!.clipPath(clipPath)
                surfaceHolder.unlockCanvasAndPost(canvas)
            }
        }
    }
}

SurfaceView实现为cutomView,并添加到activity_main.xml:

<com.example.customcomponent.CircleSurfaceView
android:id="@+id/circleSurfaceView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />

但是结果只有黑屏。

问题:如何将两个视频重叠,以便有机会移动剪切的区域? (任何kotlin或Java)

谢谢!

0 个答案:

没有答案