当前位置: 移动技术网 > 移动技术>移动开发>Android > 超级简单的android通过view自带的方法进行裁剪视图,实现圆形,矩形和圆角

超级简单的android通过view自带的方法进行裁剪视图,实现圆形,矩形和圆角

2020年08月10日  | 移动技术网移动技术  | 我要评论

使用 View.setClipToOutline() 方法或 android:clipToOutline 属性将视图裁剪至其轮廓区域。由 Outline.canClip() 方法所决定,仅有矩形、圆形和圆角矩形轮廓支持裁剪。

如果要将视图裁剪至可绘制对象的形状,请将可绘制对象设置为视图背景(如上所示)并调用 View.setClipToOutline() 方法。

比如说布局

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <LinearLayout
        android:id="@+id/imageView"
        android:layout_width="200dp"
        android:layout_height="300dp"
        android:background="@color/colorPrimary"
        android:orientation="vertical"
        android:scaleType="center"
        android:src="@mipmap/timg"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

可以是其他View,如imageview

imageView.outlineProvider = object : ViewOutlineProvider() {
            override fun getOutline(view: View, outline: Outline) {
                //矩形
                outline.setRect(Rect(0,0,view.width,view.width))
                //圆形
                //outline.setOval(0, 0, view.width, view.width)
                //圆角
                //outline.setRoundRect(0, 0, view.width, view.height, view.width / 2f)
            }
        }
//将视图裁剪至其轮廓区域
imageView.clipToOutline = true

在开发中经常用到

本文地址:https://blog.csdn.net/u010368726/article/details/107870508

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网