Reputation: 1729
I'm trying to convert a "rectangular" bitmap into a circular one with a border. I wrote this code:
using Android.Graphics;
namespace MyNamespace
{
public static class BitmapExtension
{
public static Bitmap GetCircularBitmap(this Bitmap bitmap)
{
Bitmap result = Bitmap.CreateBitmap(bitmap.Width, bitmap.Height, Bitmap.Config.Argb8888);
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
Rect rect = new Rect(0, 0, bitmap.Width, bitmap.Height);
paint.AntiAlias = true;
canvas.DrawARGB(0, 0, 0, 0);
paint.Color = Color.Black;
canvas.DrawCircle(bitmap.Width / 2, bitmap.Height / 2, bitmap.Width / 2, paint);
paint.SetXfermode(new PorterDuffXfermode(PorterDuff.Mode.SrcIn));
canvas.DrawBitmap(bitmap, rect, rect, paint);
// Border
paint.SetStyle(Paint.Style.Stroke);
paint.StrokeWidth = 2;
paint.AntiAlias = true;
canvas.DrawCircle(
canvas.Width / 2,
canvas.Width / 2,
canvas.Width / 2 - 2 / 2,
paint);
// Release pixels on original bitmap.
bitmap.Recycle();
return result;
}
}
}
This works great so far, however, since this code is used in a RecyclerView sometimes it just doesn't draw right:
As you can see, the image is drawn slightly out of place. So i got two questions:
Update: Solution
I used FFImageLoading together with a Circle Transformation to display my Images. It also improved the performance a lot and enabled a good practice for Image Caching.
Upvotes: 0
Views: 223
Reputation: 51
The easiest way would be to use CircleImageView
First add this to yout gradle file:
dependencies {
...
implementation 'de.hdodenhof:circleimageview:2.2.0'
}
In your XML layout:
<de.hdodenhof.circleimageview.CircleImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/image"
android:layout_width="24"
android:layout_height="24"
android:src="@drawable/image"/>
And in your Java code use it as you would like any other ImageView.
Upvotes: 2