[英]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.