gpt4 book ai didi

android - 如何以编程方式为布局的每个角设置不同的半径?

转载 作者:行者123 更新时间:2023-11-29 18:25:31 24 4
gpt4 key购买 nike

我有一个扩展 LinearLayouts 的 kotlin 类。我用它来为我的布局添加半径。这是类(class)。

import android.content.Context
import android.graphics.Canvas
import android.graphics.Path
import android.graphics.RectF
import android.util.AttributeSet
import android.widget.LinearLayout

class RadiusLinearLayout(context: Context, attrs: AttributeSet) : LinearLayout(context, attrs) {

private lateinit var rectF: RectF
private val path = Path()
private var cornerRadius = 25f

init {
val radiusAttribute = getContext().obtainStyledAttributes(attrs, R.styleable.RadiusLinearLayout)
cornerRadius = radiusAttribute.getFloat(R.styleable.RadiusLinearLayout_cornerRadius, 25f)
radiusAttribute.recycle()
}

override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
rectF = RectF(0f, 0f, w.toFloat(), h.toFloat())
resetPath()
}

override fun draw(canvas: Canvas) {
val save = canvas.save()
canvas.clipPath(path)
super.draw(canvas)
canvas.restoreToCount(save)
}

override fun dispatchDraw(canvas: Canvas) {
val save = canvas.save()
canvas.clipPath(path)
super.dispatchDraw(canvas)
canvas.restoreToCount(save)
}

private fun resetPath() {
path.reset()
path.addRoundRect(rectF, this.cornerRadius, this.cornerRadius, Path.Direction.CW)
path.close()
}
}

我还有一个 styleable.xml 文件,用于在 xml 布局文件上定义时设置布局的半径

<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="RadiusLinearLayout">
<attr name="cornerRadius" format="float"/>
</declare-styleable>
</resources>

这是一个例子。

    <test.com.RadiusLinearLayout
android:id="@+id/containerLinearLayoutCF"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cornerRadius="25dp"
android:orientation="vertical"/>

我想以编程方式为布局的每个角设置半径。有办法吗?

最佳答案

I would like to set the radius for each individual corner of the layout programmatically. Is there a way to do so?

是的,您需要声明函数和相应的字段来存储您的半径,如下所示:

private var topLeft = 0f
private var topRight = 0f
private var bottomLeft = 0f
private var bottomRight = 0f

public fun setRadius(topLeft: Float = 0f, topRight: Float = 0f, bottomLeft: Float = 0f, bottomRight: Float = 0f) {
this.topLeft = topLeft
...
invalidate()
}

private fun resetPath() {
path.reset()
val corners = floatArrayOf(
topLeft, topLeft,
topRight, topRight,
bottomLeft, bottomLeft,
bottomRight, bottomRight
)
path.addRoundRect(rectF, corners, Path.Direction.CW)
path.close()
}

关于android - 如何以编程方式为布局的每个角设置不同的半径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59222558/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com