@@ -3,7 +3,10 @@ package com.hfad.findme
3
3
import android.content.Context
4
4
import android.graphics.*
5
5
import android.util.AttributeSet
6
+ import android.view.MotionEvent
6
7
import androidx.appcompat.widget.AppCompatImageView
8
+ import kotlin.math.floor
9
+ import kotlin.random.Random
7
10
8
11
class SpotlightImageView @JvmOverloads constructor(
9
12
context : Context , attrs : AttributeSet ? = null
@@ -23,7 +26,7 @@ class SpotlightImageView @JvmOverloads constructor(
23
26
private val spotlight = BitmapFactory .decodeResource(resources, R .drawable.mask)
24
27
25
28
private var shader: Shader
26
- // private val shaderMatrix = Matrix()
29
+ private val shaderMatrix = Matrix ()
27
30
28
31
init {
29
32
val bitmap = Bitmap .createBitmap(spotlight.width, spotlight.height, Bitmap .Config .ARGB_8888 )
@@ -43,6 +46,11 @@ class SpotlightImageView @JvmOverloads constructor(
43
46
paint.shader = shader
44
47
}
45
48
49
+ override fun onSizeChanged (w : Int , h : Int , oldw : Int , oldh : Int ) {
50
+ super .onSizeChanged(w, h, oldw, oldh)
51
+ setupWinnerRect()
52
+ }
53
+
46
54
override fun onDraw (canvas : Canvas ) {
47
55
super .onDraw(canvas)
48
56
// Draw the BitmapShader texture
@@ -54,5 +62,53 @@ class SpotlightImageView @JvmOverloads constructor(
54
62
)
55
63
shader.setLocalMatrix(shaderMatrix)
56
64
canvas.drawRect(0.0f, 0.0f, width.toFloat(), height.toFloat() / 2, paint)*/
65
+
66
+ // Draw the Android image
67
+ canvas.drawColor(Color .WHITE )
68
+ canvas.drawBitmap(bitmapAndroid, androidBitmapX, androidBitmapY, paint)
69
+
70
+ if (! gameOver) {
71
+ if (shouldDrawSpotlight) {
72
+ canvas.drawRect(0.0f , 0.0f , width.toFloat(), height.toFloat(), paint)
73
+ } else {
74
+ canvas.drawColor(Color .BLACK )
75
+ }
76
+ }
77
+ }
78
+
79
+ override fun onTouchEvent (motionEvent : MotionEvent ): Boolean {
80
+ val motionEventX = motionEvent.x
81
+ val motionEventY = motionEvent.y
82
+ when (motionEvent.action) {
83
+ MotionEvent .ACTION_DOWN -> {
84
+ shouldDrawSpotlight = true
85
+ if (gameOver) {
86
+ gameOver = false
87
+ setupWinnerRect()
88
+ }
89
+ }
90
+ MotionEvent .ACTION_UP -> {
91
+ shouldDrawSpotlight = false
92
+ gameOver = winnerRect.contains(motionEventX, motionEventY)
93
+ }
94
+ }
95
+ shaderMatrix.setTranslate(
96
+ motionEventX - spotlight.width / 2.0f ,
97
+ motionEventY - spotlight.height / 2.0f
98
+ )
99
+ shader.setLocalMatrix(shaderMatrix)
100
+ invalidate() // redraw
101
+ return true
102
+ }
103
+
104
+ private fun setupWinnerRect () {
105
+ androidBitmapX = floor(Random .nextFloat() * (width - bitmapAndroid.width))
106
+ androidBitmapY = floor(Random .nextFloat() * (height - bitmapAndroid.height))
107
+ winnerRect = RectF (
108
+ (androidBitmapX),
109
+ (androidBitmapY),
110
+ (androidBitmapX + bitmapAndroid.width),
111
+ (androidBitmapY + bitmapAndroid.height)
112
+ )
57
113
}
58
114
}
0 commit comments