java - 我想在 kotlin 中为我的自定义 ImageView 添加圆角

标签 java android kotlin imageview

我想在 kotlin 中向我的自定义 ImageView 添加圆角,并且已创建可绘制资源文件,但无法正常工作,无法找到使用 View 的方法。SetToOutline.plz 帮助我添加圆角

kotlin 代码

import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.appcompat.widget.AppCompatImageView

class DynamicHeightImageView : AppCompatImageView {
    private var whRatio = 0f

    constructor(context: Context) : super(context)

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)

    fun setRatio(ratio: Float) {
        whRatio = ratio
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        if (whRatio != 0f) {
            val width = measuredWidth
            val height = (whRatio * width).toInt()
            setMeasuredDimension(width, height)
        }
    }

}


xml 文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

        <com.georgcantor.wallpaperapp.util.DynamicHeightImageView
            android:id="@+id/pictureImageView"
            android:layout_width="match_parent"
            android:layout_margin="5dp"
            android:background="@drawable/rounded_corner"
            android:layout_height="match_parent"
            android:contentDescription="@string/image_item"
            android:foreground="?android:attr/selectableItemBackground"
            android:scaleType="fitXY" />

</RelativeLayout>

可绘制文件

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <corners
        android:bottomLeftRadius="10dp"
        android:bottomRightRadius="10dp"
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp" />

    <stroke
        android:width="1dp"
        android:color="@color/off_white" />

    <solid android:color="@color/colorDetailPrimaryDark" />

</shape>```

最佳答案

请不要重新发明轮子。那里有一个漂亮的图书馆.. https://github.com/vinc3m1/RoundedImageView

你可以利用这个

关于java - 我想在 kotlin 中为我的自定义 ImageView 添加圆角,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60449843/

相关文章:

java - 尝试获取空数组Kotlin的长度

java - NPE at sun.nio.ch.Util.free(Util.java :199)

Android Image Capture 在里程碑上节省小尺寸

android - Kotlin - 下载文件

android - 按下imageview时更改所有背景的源图像

android - android studio 中的 gradle 问题

java - JBOSS 7.1(或 6.1)中不支持 CXF JCA 连接器?

java - Tomcat 和 JDBC 驱动程序

java - 如何创建自己的 TypifiedElement

android - 移动应用程序中 webview 和 native 代码之间的通信