文章目录
一、自定义 View 组件 ( Kotlin )
二、自定义 SurfaceView 组件 ( Kotlin )
自定义组件构造函数统一在 constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) 构造函数中实现 , 在 constructor(context: Context?) , constructor(context: Context?, attrs: AttributeSet?) 构造函数中 , 都基于三个参数的构造函数 ;
一、自定义 View 组件 ( Kotlin )
package kim.hsl.aa.view import android.content.Context import android.graphics.Canvas import android.os.Build import android.util.AttributeSet import android.view.View import androidx.annotation.RequiresApi class MyView : View { val TAG: String = "MyView" constructor(context: Context?) : this(context, null, 0) constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) @RequiresApi(Build.VERSION_CODES.LOLLIPOP) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) // 绘制核心方法 } }
二、自定义 SurfaceView 组件 ( Kotlin )
package kim.hsl.aa.view import android.content.Context import android.graphics.* import android.os.Build import android.util.AttributeSet import android.view.SurfaceHolder import android.view.SurfaceView import androidx.annotation.RequiresApi import kim.hsl.aa.R class MySurfaceView : SurfaceView, SurfaceHolder.Callback, Runnable { val TAG = "MySurfaceView" /** * 渲染绘制标志 */ private var mDrawingFlag = false /** * 渲染线程 */ private var mRender: Thread? = null /** * 画布 */ private var mCanvas: Canvas? = null constructor(context: Context) : this(context, null, 0) constructor(context: Context, attrs : AttributeSet?) : this(context, attrs, 0) constructor(context: Context, attrs: AttributeSet?, defStyleAttr : Int) : super(context, attrs, defStyleAttr) { holder.addCallback(this) setZOrderOnTop(true) holder.setFormat(PixelFormat.TRANSLUCENT) } @RequiresApi(Build.VERSION_CODES.LOLLIPOP) constructor(context: Context, attrs: AttributeSet, defStyleAttr : Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) override fun run() { val paint = Paint() while (mDrawingFlag) { paint.setColor(Color.WHITE) mCanvas = holder.lockCanvas() if (mCanvas == null) continue mCanvas?.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR) //TODO 绘制逻辑 holder.unlockCanvasAndPost(mCanvas) Thread.sleep(20) } } /* 下面的三个函数是 实现 SurfaceHolder.Callback 接口方法 */ override fun surfaceChanged(holder: SurfaceHolder?, format: Int, width: Int, height: Int) { mDrawingFlag = true mRender = Thread(this) mRender?.start() // 加载图片 var bitmap = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher) } override fun surfaceDestroyed(holder: SurfaceHolder?) { } override fun surfaceCreated(holder: SurfaceHolder?) { } }