【问题标题】:Whats the best way to convert a bitmap into a circular bitmap将位图转换为圆形位图的最佳方法是什么
【发布时间】:2018-04-24 08:59:01
【问题描述】:

我正在尝试将“矩形”位图转换为带边框的圆形位图。我写了这段代码:

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 中使用,有时它只是无法正确绘制:

如您所见,图像画得有些不合适。所以我有两个问题:

  1. 发生这种奇怪行为的原因是什么?
  2. 有没有办法改进我的 GetCircularBitmap 方法?由于性能很重要,它必须非常快。

更新:解决方案

我使用FFImageLoadingCircle Transformation 来显示我的图像。它还大大提高了性能,并为图像缓存提供了良好的实践。

【问题讨论】:

  • 第二个结果不就是因为第二个图像不是正方形的吗?您只需首先切掉它的中心正方形并使用它。

标签: java c# android image-processing bitmap


【解决方案1】:

最简单的方法是使用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 一样。

【讨论】:

  • 谢谢,我会试一试,因为当涉及到性能问题时,我对第三方库有点怀疑。
  • 我在 RecyclerView 中使用过,没有遇到任何问题。不过也许你可以看看 GitHub 仓库中的代码?
  • 我试过了。对于其他应用程序可能是一个很好的解决方案,但是由于我以异步方式将图像加载到 CircleImageView 并在我回来时使用 SetImageBitmap 以某种方式无法解决。代码从异步请求返回后,图像不会显示(但是它与我在入门帖子中发布的我自己的代码一起使用)。
  • 你从哪里加载图片?
  • 如果您从网络加载图像,我会说使用毕加索是最好的方法。您不必担心 AsyncTasks 或 Loaders。 square.github.io/picasso
猜你喜欢
  • 1970-01-01
  • 2013-10-05
  • 1970-01-01
  • 1970-01-01
  • 2018-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多