Skip to content

Instantly share code, notes, and snippets.

@JyotimoyKashyap
Last active January 28, 2023 12:06
Show Gist options
  • Select an option

  • Save JyotimoyKashyap/df1213b11b59f3b5fb28f7b5ad4d3abe to your computer and use it in GitHub Desktop.

Select an option

Save JyotimoyKashyap/df1213b11b59f3b5fb28f7b5ad4d3abe to your computer and use it in GitHub Desktop.
This gist is an example of handling Surface View in Android in Kotlin in a better way
class LiveGraphPlotView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null
) : SurfaceView(context, attrs), SurfaceHolder.Callback, Runnable {
private lateinit var mCanvas: Canvas
private lateinit var mSurfaceHolder: SurfaceHolder
private var mWidth: Int = 0
private var mHeight: Int = 0
private var mRunning: Boolean = false
init {
holder.addCallback(this)
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
mWidth = w
mHeight = h
}
override fun surfaceCreated(holder: SurfaceHolder) {
mSurfaceHolder = holder.apply {
setFormat(PixelFormat.TRANSPARENT)
}
Thread(this, "thread-105").start()
mRunning = true
}
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {}
override fun surfaceDestroyed(holder: SurfaceHolder) {
if (::mSurfaceHolder.isInitialized && holder == mSurfaceHolder) {
mRunning = false
}
}
override fun run() {
while (mRunning) {
if (mSurfaceHolder.surface.isValid) {
try {
mCanvas =
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) mSurfaceHolder.lockCanvas()
else mSurfaceHolder.lockHardwareCanvas()
mCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)
mCanvas.save()
// do changes to your canvas
mCanvas.restore()
mSurfaceHolder.unlockCanvasAndPost(mCanvas)
} catch (e: Exception) {
OrbiLogger.e(TAG, "Exception : ${e.localizedMessage}")
}
}
}
}
companion object {
private val TAG = // TAG Name
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment