天天看點

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

可以看到圖檔上面已經被設定為圓角。

上面截圖是我做的自定義的更新彈框,在後面會寫一篇部落格介紹怎麼實作,歡迎關注。

另外,有什麼問題,歡迎留言~