【Kotlin】自定义View(一)

关于kotlin基础语法知识可以在菜鸟教程上学习。

【Kotlin】自定义View(一)_第1张图片

整个界面的具体逻辑分析Android 弧形ViewPager 和弧形HeaderView这篇博客



@SuppressLint("ViewConstructor")
class PerfectArcView(context: Context, @ColorInt private var startColor: Int, @ColorInt private var endColor: Int) : View(context) {

    private val mPaint: Paint = Paint()
    private var mHeight: Int = 0
    private var mWidth: Int = 0
    private var mRadius: Int = 0
    private var mCx: Int = 0
    private var mCy: Int = 0
    private var mRectF:RectF= RectF()

    private  var mBitmap:Bitmap
    private lateinit var  mLinearGradient:LinearGradient


    init {

        mPaint.color = Color.BLUE
        mPaint.strokeWidth = 10f
        mPaint.style = Paint.Style.FILL
        mPaint.isAntiAlias = true
        mBitmap=BitmapFactory.decodeResource(context.resources,R.mipmap.icon_photo)
    }



    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        mWidth = w
        mHeight = h

        mRadius = mWidth

        mCx = w / 2
        mCy = h - w * 2

        mRectF.top=0f
        mRectF.left=0f
        mRectF.bottom=mHeight.toFloat()
        mRectF.right=mWidth.toFloat()


        mLinearGradient = LinearGradient(mWidth / 2f, 0f, mWidth / 2f, mHeight.toFloat(), startColor, endColor, Shader.TileMode.MIRROR)

    }





    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    @SuppressLint("DrawAllocation")
    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)

        var layerId:Int =canvas!!.saveLayer(mRectF, mPaint)

        canvas!!.drawCircle(mCx.toFloat(), mCy.toFloat(), mRadius.toFloat(), mPaint)
        mPaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)



//        mPaint.shader=mLinearGradient//绘制渐变色
//        canvas!!.drawRect(mRectF, mPaint)
        canvas.drawBitmap(mBitmap,null,mRectF,mPaint)


        mPaint.xfermode=null
        canvas.restoreToCount(layerId)

    }
}

知识点:

  • 过渡模式 – PorterDuffXfermode
  • 图层 – Layer

你可能感兴趣的:(Kotlin)