天天看点

Android: 实现圆角ImageView

实现圆角imageview有两种办法:

1.  xml中设置background:

drawable文件夹中新建一个文件bg_update_dialog:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/base_dialog_background_color" />
    <corners android:radius="@dimen/update_dialog_corner_radius" />
</shape>
           

然后再布局文件中引用:

android:background="@drawable/bg_update_dialog"
           

上面这种方法在有些情况下有用,但在某些情况下可能出现下面的状况:

上边角不是圆角

Android: 实现圆角ImageView

这种情况用第二种方法。

2. 在代码中设置。

大概的原理就是将图片转化为Bitmap格式的,然后bitmap格式转化为RundedBitmapDrawable:

在oncreate中设置:

setContentView(R.layout.dialog_update);
        ImageView image = findViewById(R.id.image);
        RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(context.getResources(), BitmapFactory.decodeResource(context.getResources(), R.drawable.update_banner));
        circularBitmapDrawable.setCornerRadius(15);
        image.setImageDrawable(circularBitmapDrawable);
           

此时的效果为:

Android: 实现圆角ImageView

可以看到图片上面已经被设置为圆角。

上面截图是我做的自定义的升级弹框,在后面会写一篇博客介绍怎么实现,欢迎关注。

另外,有什么问题,欢迎留言~