Skip to content

Instantly share code, notes, and snippets.

@markfarber
Created June 25, 2021 00:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markfarber/a8fa7b678ef284027c620438e5012e29 to your computer and use it in GitHub Desktop.
Save markfarber/a8fa7b678ef284027c620438e5012e29 to your computer and use it in GitHub Desktop.
package com.example.flightgear.view
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PointF
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
class JoystickView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
val p = Paint().apply {
color = Color.BLACK
isAntiAlias = true
style = Paint.Style.FILL
}
var circleRadius = 0f
var center = PointF()
var defaultCenter = PointF()
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
Log.i(":::JoystickView", "@onSizeChanged -> called wit w = $w h = $h")
super.onSizeChanged(w, h, oldw, oldh)
circleRadius = minOf(w, h) / 4.0f
center = PointF(w / 2.0f, h / 2.0f)
defaultCenter = PointF(w / 2.0f, h / 2.0f)
invalidate()
}
override fun onDraw(canvas: Canvas?) {
canvas?.drawCircle(center.x, center.y, circleRadius, p)
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
event?.let { e ->
when (e.action) {
MotionEvent.ACTION_MOVE -> updateView(e.x, e.y)
MotionEvent.ACTION_UP -> resetView()
else -> {
/*ignore*/
}
}
return true
} ?: return true
}
private fun resetView() {
center = defaultCenter
}
private fun updateView(x: Float, y: Float) {
center = PointF(x, y)
invalidate()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment