【android】使用drawable的xml文件和View.setClipToOutline()製作圓形ImageView

先寫一個xml文件

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="50dp" />
</shape>

定義一個矩形,圓角爲50dp

然後設置ImageView的background爲此文件

<ImageView
    android:id="@+id/imageView"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:background="@drawable/image_background"
    android:scaleType="fitXY"
    app:srcCompat="@drawable/b" />

然後在Activity中

獲取ImageView ,然後調用setClipToOutline方法

ImageView imageView=findViewById(R.id.imageView);
if (Build.VERSION.SDK_INT >=       
    Build.VERSION_CODES.LOLLIPOP) {
    imageView.setClipToOutline(true);
}

PS:

Clipping views is an expensive operation, so don't animate the shape you use to clip a view. To achieve this effect, use the Reveal Effect animation.
這是谷歌的原話,也就是說謹慎使用,不過切割個靜態圖片應該沒什麼。
這應該是獲得圓形ImageView的最簡單方法,但對Android版本有要求,而且在測試時,也有不生效的情況

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章