实现圆图的方法有很多种,这是一种使用轮廓和剪切。
通过setOutLineProvider提供一个轮廓
通过setClipToOutLine(true)来让视图按轮廓剪切
代码很简单:
布局activity_main.xml
,上面是原图,下面是圆图:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#9f9"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="150dp"
android:scaleType="centerInside"
android:src="@drawable/cat" />
<ImageView
android:id="@+id/iv1"
android:layout_width="match_parent"
android:layout_height="150dp"
android:src="@drawable/cat"/>
</LinearLayout>
代码:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
with(iv1) {
scaleType = ImageView.ScaleType.CENTER_INSIDE
clipToOutline = true
outlineProvider = object : ViewOutlineProvider() {
override fun getOutline(view: View?, outline: Outline) {
view as ImageView
val radius = Math.min(view.width, view.height) / 2
val centerX = (view.right - view.left) / 2
val centerY = (view.bottom - view.top) / 2
outline.setOval(centerX - radius, centerY - radius, centerX + radius, centerY + radius)
}
}
}
}
}