用kotlin语言自定义个五角星view
时间: 2023-11-06 14:04:42 浏览: 159
Android 使用Kotlin自定义View的方法教程
以下是一个用Kotlin语言自定义的五角星View的示例:
```kotlin
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
class StarView(context: Context, attrs: AttributeSet) : View(context, attrs) {
private val paint = Paint()
private var starSize = 0f
private var starColor = 0
init {
paint.isAntiAlias = true
paint.style = Paint.Style.FILL
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.StarView)
starSize = typedArray.getDimension(R.styleable.StarView_starSize, 0f)
starColor = typedArray.getColor(R.styleable.StarView_starColor, 0)
typedArray.recycle()
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas?.let {
val centerX = width / 2f
val centerY = height / 2f
val outerRadius = starSize / 2f
val innerRadius = outerRadius / 2.63f
val rotationAngle = Math.PI / 2
val points = arrayOf(
Pair(centerX, centerY - outerRadius),
Pair(centerX + innerRadius * Math.cos(rotationAngle).toFloat(), centerY - innerRadius * Math.sin(rotationAngle).toFloat()),
Pair(centerX + outerRadius * Math.cos(rotationAngle / 2).toFloat(), centerY - outerRadius * Math.sin(rotationAngle / 2).toFloat()),
Pair(centerX + innerRadius * Math.cos(rotationAngle / 2 * 3).toFloat(), centerY - innerRadius * Math.sin(rotationAngle / 2 * 3).toFloat()),
Pair(centerX + outerRadius * Math.cos(rotationAngle * 2).toFloat(), centerY - outerRadius * Math.sin(rotationAngle * 2).toFloat()),
Pair(centerX, centerY + innerRadius),
Pair(centerX - outerRadius * Math.cos(rotationAngle * 2).toFloat(), centerY - outerRadius * Math.sin(rotationAngle * 2).toFloat()),
Pair(centerX - innerRadius * Math.cos(rotationAngle / 2 * 3).toFloat(), centerY - innerRadius * Math.sin(rotationAngle / 2 * 3).toFloat()),
Pair(centerX - outerRadius * Math.cos(rotationAngle / 2).toFloat(), centerY - outerRadius * Math.sin(rotationAngle / 2).toFloat()),
Pair(centerX - innerRadius * Math.cos(rotationAngle).toFloat(), centerY - innerRadius * Math.sin(rotationAngle).toFloat())
)
paint.color = starColor
canvas.drawVertices(
Canvas.VertexMode.TRIANGLE_FAN,
points.size,
points.flatMap { listOf(it.first, it.second) }.toFloatArray(),
0,
null,
0,
null,
0,
null,
0,
0,
paint
)
}
}
fun setStarSize(starSize: Float) {
this.starSize = starSize
invalidate()
}
fun setStarColor(starColor: Int) {
this.starColor = starColor
invalidate()
}
}
```
这个自定义View继承自Android中的View类,并覆盖了onDraw方法来绘制五角星。
在构造函数中初始化了一个Paint对象,并从属性集中读取了星星的大小和颜色。在onDraw方法中,我们首先计算了五角星的十个点的坐标,然后使用Canvas.drawVertices方法来绘制五角星。
最后,我们在自定义View中提供了两个setter方法,可以动态地改变星星的大小和颜色。
阅读全文