Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
1.7 kB
3
Indexable
Never
package com.example.sample

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View

class SimpleCircle(context: Context?, attrs: AttributeSet?) : View.OnTouchListener,
    View(context, attrs) {
    private val RADIUS = 60f
    private var xCoor = RADIUS
    private var yCoor = RADIUS
    private var rightDX = 0f
    private var rightDY = 0f

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        val viewPaint = Paint()
        viewPaint.color = Color.RED
        viewPaint.isAntiAlias = true
        canvas?.drawCircle(xCoor, yCoor, RADIUS, viewPaint)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        setMeasuredDimension((RADIUS * 2).toInt(), (RADIUS * 2).toInt())

    }



    override fun onTouch(view: View?, event: MotionEvent?): Boolean {
        // This is not called
        event ?: return false
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                rightDX = view!!.x - event.rawX
                rightDY = view.y - event.rawY
            }
            MotionEvent.ACTION_MOVE -> {
                val displacement = event.rawX + rightDX
                view!!.animate()
                    .x(displacement)
                    .y(event.rawY + rightDY)
                    .setDuration(0)
                    .start()
                invalidate()
            }
            else -> {
                return false
            }
        }
        return true
    }


}