activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <com.example.myapplication.DrawingView android:id="@+id/drawingView" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout> |
DrawingView.kt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
package com.example.myapplication import android.content.Context import android.graphics.* import android.util.AttributeSet import android.view.MotionEvent import android.view.View class DrawingView(context: Context, attrs: AttributeSet) : View(context, attrs) { private val path = Path() private val paint = Paint().apply { isAntiAlias = true color = Color.BLACK style = Paint.Style.STROKE strokeWidth = 10f strokeJoin = Paint.Join.ROUND strokeCap = Paint.Cap.ROUND } private var currentX = 0f private var currentY = 0f override fun onDraw(canvas: Canvas) { super.onDraw(canvas) canvas.drawPath(path, paint) } override fun onTouchEvent(event: MotionEvent): Boolean { val x = event.x val y = event.y when (event.action) { MotionEvent.ACTION_DOWN -> { path.moveTo(x, y) currentX = x currentY = y return true } MotionEvent.ACTION_MOVE -> { path.quadTo(currentX, currentY, (x + currentX) / 2, (y + currentY) / 2) currentX = x currentY = y invalidate() return true } MotionEvent.ACTION_UP -> { path.lineTo(currentX, currentY) invalidate() return true } else -> return super.onTouchEvent(event) } } } |
MainActivity.kt
1 2 3 4 5 6 7 8 9 10 11 12 |
package com.example.myapplication import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } } |
