【Android音视频学习之路(一)】如何在 Android 平台绘制一张图片

1,591 阅读1分钟

前言

最近音视频挺火的,所以学习还是挺有必要的,这儿是自己的学习笔记~~慢慢来吧

视频的本质就是多张图片嘛,所以先来说说图片的绘制

1.ImageView 绘制图片

这个想必做过Android开发的都知道如何去绘制了。很简单:

  val path = applicationContext.cacheDir.absolutePath + File.separator + "image.jpg"
  val bitmap = BitmapFactory.decodeFile(path)
  binding.imageView.setImageBitmap(bitmap)

2. SurfaceView 绘制图片

这个比 ImageView 绘制图片稍微复杂一点点:

 binding.surface.holder.addCallback(object : SurfaceHolder.Callback {
            override fun surfaceCreated(surfaceHolder: SurfaceHolder) {
                val paint = Paint()
                paint.isAntiAlias = true //抗锯齿
                paint.style = Paint.Style.STROKE //仅描边

                val path = applicationContext.cacheDir.absolutePath + File.separator + "image.jpg"
                val bitmap = BitmapFactory.decodeFile(path)

                val canvas = surfaceHolder.lockCanvas() // 先锁定当前surfaceView的画布
                canvas.drawBitmap(bitmap, 0f, 0f, paint); //执行绘制操作
                surfaceHolder.unlockCanvasAndPost(canvas); // 解除锁定并显示在界面上
            }

            override fun surfaceChanged(surfaceHolder: SurfaceHolder, p1: Int, p2: Int, p3: Int) { }

            override fun surfaceDestroyed(surfaceHolder: SurfaceHolder) { }
        })

3.自定义 View 绘制图片

这个有绘制自定义View经验的可以很轻松的完成

class CustomView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val bitmap: Bitmap
    private val paint = Paint()
    init {
        paint.isAntiAlias = true //抗锯齿
        paint.style = Paint.Style.STROKE //仅描边

        val path = context.cacheDir.absolutePath + File.separator + "image.jpg"
        bitmap = BitmapFactory.decodeFile(path)
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        // 不建议在onDraw做任何分配内存的操作
        canvas?.drawBitmap(bitmap, 0f, 0f, paint);
    }
}

注:如果是使用非自己文件目录下,别忘记了权限,否则是不会展示成功的。

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

下一篇就是各种API相关的了