如何使用RoundedBitmapDrawable

gia*_*200 57 android android-drawable android-bitmap

有人设法使用RoundedBitmapDrawable?如果我错了,请纠正我,但根据我的理解,它会从常规矩形图像中生成圆形图像.

到目前为止我尝试过的是这个

RoundedBitmapDrawable.createRoundedBitmapDrawable(getResources(), BitmapFactory.decodeResource(getResources(), iconResource))
Run Code Online (Sandbox Code Playgroud)

我试图实现的目标:将任何图像转换为圆形图像并使用ImageView显示它.

如果我把事情搞混了,我所说的都是无意义的.是否可以(或更简单)使用任何新框架?(Android L或新的支持库)

ala*_*anv 111

您需要设置角半径.

Resources res = getResources();
Bitmap src = BitmapFactory.decodeResource(res, iconResource);
RoundedBitmapDrawable dr =
    RoundedBitmapDrawableFactory.create(res, src);
dr.setCornerRadius(Math.max(src.getWidth(), src.getHeight()) / 2.0f);
imageView.setImageDrawable(dr);
Run Code Online (Sandbox Code Playgroud)

  • 有`dr.setCircular(真)` (15认同)
  • 非方形图像作为输入怎么样?根据我的看法,在这种情况下输出被拉伸.有没有办法使用中心作物? (2认同)

小智 61

这可能是一个迟到的回复,但我希望它会对其他人有所帮助

如果您的图像具有相同的宽度和高度,那么您可以简单地将setCircular设置为true以获得如下的圆形位图

RoundedBitmapDrawable drawable = RoundedBitmapDrawableFactory.create(getResources(),your_bitmap);
drawable.setCircular(true);
Run Code Online (Sandbox Code Playgroud)

  • 工具栏徽标不接受`RoundedBitmapDrawable`所以如何从中获取圆形位图?`getBitmap`返回原始位图 (2认同)

Mil*_*ank 8

我也在寻找圆形图像视图以提高效率我已经搜索了所有第三方库我发现所有这些都是他们正在创建新的位图这是繁琐的任务列表其消耗更多的内存

参考图书馆:

  1. http://ruibm.com/2009/06/16/rounded-corner-bitmaps-on-android/
  2. https://github.com/vinc3m1/RoundedImageView
  3. https://github.com/lopspower/CircularImageView

从这个图书馆,我用过

https://github.com/vinc3m1/RoundedImageView

因为基于Romain Guy的原始示例支持圆角(和椭圆或圆圈)的快速ImageView(和Drawable)

  • 不会创建原始位图的副本
  • 不使用不是硬件加速且没有消除锯齿的clipPath.
  • 不使用setXfermode剪切位图并将两次绘制到画布.


Lak*_*aza 6

完整代码:

ImageView img= (ImageView) findViewById(R.id.yourimageid);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.yourpictureresource);

RoundedBitmapDrawable rnd = (RoundedBitmapDrawable) RoundedBitmapDrawableFactory.create(getResources(), bitmap);
rnd.setCircular(true);
img.setImageDrawable(rnd);
Run Code Online (Sandbox Code Playgroud)