简体   繁体   中英

Whats the best way to convert a bitmap into a circular bitmap

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:

  1. What causes this strange behavior to happen?
  2. Is there a way to improve my GetCircularBitmap Method? Since performance is important, it must be very fast.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM