Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Background View Rendering
package com.ozodrukh.pictureexploration
import android.content.Context
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Picture
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import java.util.*
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
class MainActivity : AppCompatActivity() {
private lateinit var surface: PictureView
private val ioExecutor = Executors.newScheduledThreadPool(1)
private val picture = Picture()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
surface = PictureView(this)
setContentView(surface)
val random = Random()
ioExecutor.scheduleAtFixedRate ({
val imageId: Int = when(random.nextInt(2)){
0 -> R.drawable.image
else -> R.drawable.image2
}
val bitmap = BitmapFactory.decodeResource(resources, imageId)
val start = System.currentTimeMillis()
val canvas = picture.beginRecording(300, 300)
canvas.drawBitmap(bitmap, 0.0f, 0.0f, null)
picture.endRecording()
Log.i("PictureView", "record ended in ${System.currentTimeMillis() - start}")
bitmap.recycle()
runOnUiThread {
surface.picture = picture
}
}, 0, 1, TimeUnit.SECONDS)
}
class PictureView(context: Context) : View(context) {
internal var picture: Picture? = null
set(value) {
invalidate()
field = value
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
picture?.let {
val start = System.currentTimeMillis()
Log.i("PictureView", "drawing a picture")
canvas.drawPicture(picture)
Log.i("PictureView", "drawing a picture in ${System.currentTimeMillis() - start}")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment