Created
July 4, 2024 07:45
-
-
Save imandaliya/a3ed652b5c427c8474005c52c18d63db to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context | |
import android.graphics.Canvas | |
import android.graphics.Paint | |
import android.graphics.Path | |
import android.util.AttributeSet | |
import android.view.View | |
class TransparentGridRectView @JvmOverloads constructor( | |
context: Context, attrs: AttributeSet? = null, defStyle: Int = 0 | |
) : View(context, attrs, defStyle) { | |
private val blackPaint = Paint().apply { | |
color = 0xFF000000.toInt() // Green color | |
style = Paint.Style.FILL | |
} | |
private val grayPaint = Paint().apply { | |
color = 0xFF888888.toInt() // Red color | |
style = Paint.Style.FILL | |
} | |
override fun onDraw(canvas: Canvas) { | |
super.onDraw(canvas) | |
var boxSize = 50f // Size of each box | |
// Calculate the center of the view | |
val centerX = width / 2f | |
val centerY = height / 2f | |
// Calculate the radius for the circular clipping path | |
val radius = Math.min(centerX, centerY) | |
// Create a circular path | |
val circularPath = Path().apply { | |
addCircle(centerX, centerY, radius, Path.Direction.CW) | |
} | |
// Save the canvas state before clipping | |
val saveCount = canvas.save() | |
// Clear the canvas with a transparent color | |
canvas.drawColor(0, android.graphics.PorterDuff.Mode.CLEAR) | |
// Clip the canvas to the circular path | |
canvas.clipPath(circularPath) | |
// Calculate the number of boxes that can fit in each direction from the center | |
val numColumns = (width / boxSize).toInt() | |
val numRows = (height / boxSize).toInt() | |
// Start drawing from the center | |
for (row in -numRows..numRows) { | |
for (col in -numColumns..numColumns) { | |
val left = centerX + (col * boxSize) | |
val top = centerY + (row * boxSize) | |
val right = left + boxSize | |
val bottom = top + boxSize | |
// Alternate between green and red boxes | |
val paint = if ((row + col) % 2 == 0) blackPaint else grayPaint | |
canvas.drawRect(left, top, right, bottom, paint) | |
} | |
} | |
// Restore the canvas state to remove clipping | |
canvas.restoreToCount(saveCount) | |
} | |
// override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { | |
// super.onMeasure(widthMeasureSpec, widthMeasureSpec) | |
// } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment