Skip to content

Instantly share code, notes, and snippets.

@kitek
Created February 14, 2017 13:10
Show Gist options
  • Save kitek/3481cdeb30ae25e5f3470eb80be7a61a to your computer and use it in GitHub Desktop.
Save kitek/3481cdeb30ae25e5f3470eb80be7a61a to your computer and use it in GitHub Desktop.
TriangleShapeView
package your.package.name
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
class TriangleShapeView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0
) : View(context, attrs, defStyle) {
var text = ""
set(value) {
field = value
textPaint.getTextBounds(value, 0, value.length, textBounds)
invalidate()
}
private val fillPaint = Paint()
private val textPaint = Paint()
private val textBounds = Rect()
private val fillPath = Path()
init {
val scale = resources.displayMetrics.density
fillPaint.color = Color.parseColor("#4d000000")
fillPaint.isAntiAlias = true
textPaint.isAntiAlias = true
textPaint.color = Color.WHITE
textPaint.textSize = 16 * scale
textPaint.typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
textPaint.getTextBounds(text, 0, text.length, textBounds)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val desiredWidth = Math.round(textBounds.width() * 2f)
val widthMode = MeasureSpec.getMode(widthMeasureSpec)
val widthSize = MeasureSpec.getSize(widthMeasureSpec)
val width: Int
if (widthMode == MeasureSpec.EXACTLY) {
width = widthSize
} else if (widthMode == MeasureSpec.AT_MOST) {
width = Math.min(desiredWidth, widthSize)
} else {
width = desiredWidth
}
setMeasuredDimension(width, width)
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
fillPath.reset()
fillPath.moveTo(0f, 0f)
fillPath.lineTo(width.toFloat(), height.toFloat())
fillPath.lineTo(width.toFloat(), 0f)
fillPath.close()
canvas?.let {
it.drawPath(fillPath, fillPaint)
it.save()
it.rotate(45f, width / 2f, height / 2f)
it.drawText(text, width / 2f - textBounds.width() / 2f, height / 4f + textBounds.height() / 2f, textPaint)
it.restore()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment