Android Snippet: Circle Image
A few months ago I was working on a project which required me to build a class that would download an image form the web, decode it, crop it, and show it in a circle – with a transparent background behind it, because it had to sit on top of different layout views.
I was only reminded of that seeing Romain Guy‘s blog post regarding images with rounded corners.
The end goal was to show the image just like an ImageView, only in a circle. This required me to extend a View and override the onDraw method to show it.
The circle part was tricky, so I thought I’d share that piece of code…
|
1 2 3 4 5 |
protected void onDraw(Canvas canvas){ super.onDraw(canvas); // rest of the code goes here... } |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// init shader BitmapShader shader; shader = new BitmapShader(originalBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); // init paint Paint paint = new Paint(); paint.setAntiAlias(true); paint.setShader(shader); int circleCenter = width / 2; // circleCenter is the x or y of the view's center // radius is the radius in pixels of the cirle to be drawn // paint contains the shader that will texture the shape canvas.drawCircle(circleCenter, circleCenter, radus, paint); |






