Kotlin01.手指小球
程序员文章站
2022-06-22 17:18:54
activity_main.xml
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/root"
tools:context=".MainActivity"
android:orientation="horizontal">
<com.example.a01helloworld.DrawView
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
MainActivity.kt
package com.example.a01helloworld
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
class MainActivity : AppCompatActivity() {
private var images = intArrayOf(R.mipmap.bg1, R.mipmap.bg2, R.mipmap.bg3, R.mipmap.bg4)
private var currentImg = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val root = findViewById<LinearLayout>(R.id.root)
val draw = DrawView(this)
draw.minimumWidth = 500
draw.minimumHeight = 300
root.addView(draw)
}
}
DrawView.kt
package com.example.a01helloworld
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 DrawView : View{
private var currentX = 40f
private var currentY = 50f
private var p = Paint()
constructor(context : Context) : super(context)
constructor(context: Context, set: AttributeSet) : super(context, set)
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
p.color = Color.RED
canvas!!.drawCircle(currentX, currentY, 15F, p)
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
currentX = event!!.x
currentY = event!!.y
invalidate()
return true
}
}
本文地址:https://blog.csdn.net/augfun/article/details/107503013