【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版本有要求,而且在测试时,也有不生效的情况

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