Android Canvas drawPath draws a circle that follows the movement of the finger, Kotlin

Android Canvas drawPath draws a circle that follows the movement of the finger, Kotlin

 

 

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.os.Bundle
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatImageView


class MainActivity : AppCompatActivity() {
    private var image: MyImage? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        image = findViewById(R.id.image)
    }
}

class MyImage : AppCompatImageView {
    private var mIsDraw = false
    private var curX: Float? = 0f
    private var curY: Float? = 0f

    constructor(ctx: Context, attrs: AttributeSet) : super(ctx, attrs) {

    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        when (event?.actionMasked) {
            MotionEvent.ACTION_DOWN -> {
                mIsDraw = true
            }

            MotionEvent.ACTION_MOVE -> {
                curX = event?.x
                curY = event?.y

                invalidate()
            }

            MotionEvent.ACTION_UP -> {
                mIsDraw = false
            }
        }

        return true
    }

    override fun draw(canvas: Canvas) {
        super.draw(canvas)

        if (mIsDraw) {
            myDraw(canvas)
        }
    }

    private fun myDraw(canvas: Canvas) {
        val path = Path()
        val radius = 250f

        val paint = Paint(Paint.ANTI_ALIAS_FLAG)
        paint.color = Color.RED
        paint.style = Paint.Style.STROKE
        paint.strokeWidth = 20f

        path.addCircle(curX!!, curY!!, radius, Path.Direction.CW)

        canvas.drawPath(path, paint)
    }
}

 

 

49438d74d92c4fa6931f5ca8d850b775.png

 

 

 

 

 

Android SurfaceView Simple Example-CSDN blog article has been viewed 2.3k times. Android SurfaceView Simple Example SurfaceView and View in Android are very different, and their application scenarios are different. Most of the things View can do, SurfaceView can do, but SurfaceView is more efficient. Android's View drawing process is controlled by the Android system, and the refresh mechanism is difficult for developers to control. SurfaceView supports high-frequency, multi-threaded drawing. Does SurfaceView not exist in Android U https://blog.csdn.net/zhangphil/article/details/77961909

 

Guess you like

Origin blog.csdn.net/zhangphil/article/details/135166305