[英]Whats the best way to convert a bitmap into a circular bitmap
我正在嘗試將“矩形”位圖轉換為帶有邊框的圓形位圖。 我寫了這段代碼:
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;
}
}
}
到目前為止,它的效果很好,因為此代碼有時在RecyclerView中使用,但有時繪制不正確:
如您所見,圖像繪制的位置略有偏移。 所以我有兩個問題:
更新:解決方案
我將FFImageLoading與Circle Transformation一起使用來顯示圖像。 它還大大提高了性能,並為圖像緩存提供了良好的實踐。
最簡單的方法是使用CircleImageView
首先將其添加到您的gradle文件中:
dependencies { ... implementation 'de.hdodenhof:circleimageview:2.2.0' }
在您的XML布局中:
<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"/>
並在Java代碼中像使用任何其他ImageView一樣使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.