Created
September 4, 2018 14:19
-
-
Save AdrianoCelentano/45fe0089ceccb009dd93574acc711db2 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
class HexogenImageView @JvmOverloads constructor(context: Context, | |
attrs: AttributeSet? = null, | |
defStyleAttr: Int = 0 | |
) : ImageView(context, attrs, defStyleAttr) { | |
private var path: Path | |
private var paint: Paint | |
init { | |
path = Path() | |
paint = Paint() | |
} | |
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { | |
super.onMeasure(widthMeasureSpec, heightMeasureSpec) | |
path.moveTo(measuredWidth / 2f, 0f) | |
path.lineTo(measuredWidth.toFloat(), measuredHeight * 0.3f) | |
path.lineTo(measuredWidth.toFloat(), measuredHeight * 0.6f) | |
path.lineTo(measuredWidth / 2f, measuredHeight.toFloat()) | |
path.lineTo(0f, measuredHeight * 0.6f) | |
path.lineTo(0f, measuredHeight * 0.3f) | |
path.lineTo(measuredWidth / 2f, 0f) | |
} | |
override fun onDraw(canvas: Canvas) { | |
val shader: BitmapShader | |
val bitmap = getBitmapFromDrawable(drawable) | |
shader = BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP) | |
paint.setDither(true); // set the dither to true | |
paint.setStrokeJoin(Paint.Join.ROUND); // set the join to round you want | |
paint.setStrokeCap(Paint.Cap.ROUND); // set the paint cap to round too | |
paint.setPathEffect(CornerPathEffect(20f) ); // set the path effect when they join. | |
paint.setAntiAlias(true); | |
paint.setShader(shader) | |
canvas.drawPath(path, paint) | |
} | |
private fun getBitmapFromDrawable(drawable: Drawable?): Bitmap? { | |
if (drawable == null) { | |
return null | |
} | |
if (drawable is BitmapDrawable) { | |
return drawable.bitmap | |
} | |
try { | |
val bitmap: Bitmap | |
if (drawable is ColorDrawable) { | |
bitmap = Bitmap.createBitmap(2, 2, Bitmap.Config.ARGB_8888) | |
} else { | |
bitmap = Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888) | |
} | |
val canvas = Canvas(bitmap) | |
drawable.setBounds(0, 0, canvas.width, canvas.height) | |
drawable.draw(canvas) | |
return bitmap | |
} catch (e: Exception) { | |
e.printStackTrace() | |
return null | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment