我有以下课程:
internal class V(context: Context?) : View(context) {
var path: Path = Path()
var paint: Paint = Paint(Paint.ANTI_ALIAS_FLAG)
var length: Float = 0f
var intervals: FloatArray = floatArrayOf(0f, 0f)
init {
paint.color = Color.GREEN
paint.style = Paint.Style.STROKE
paint.strokeWidth = 20f
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
path.reset()
val rect = RectF(0f, 0f, w.toFloat(), h.toFloat())
val inset = paint.strokeWidth
rect.inset(inset, inset)
path.addRoundRect(rect, 100f, 100f, Path.Direction.CW)
length = PathMeasure(path, false).length
intervals[1] = length
intervals[0] = intervals[1]
val effect: PathEffect = DashPathEffect(intervals, length)
paint.setPathEffect(effect)
}
fun setProgress(progress: Int) {
val effect: PathEffect = DashPathEffect(intervals, length - length * progress / 100)
paint.setPathEffect(effect)
invalidate()
}
override fun onDraw(canvas: Canvas) {
canvas.drawPath(path, paint)
}
}
在我的
Activity#onCreate
中我可以这样使用:
val ll = LinearLayout(this)
ll.orientation = LinearLayout.VERTICAL
val sb = SeekBar(this)
ll.addView(sb)
val v = V(this)
ll.addView(v)
setContentView(ll)
val sbcl: SeekBar.OnSeekBarChangeListener = object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
v.setProgress(progress)
}
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onStopTrackingTouch(seekBar: SeekBar) {}
}
sb.setOnSeekBarChangeListener(sbcl)
现在,每当我拖动滑块时,边框都会从左下角绘制。如何使边框从左上角开始绘制? (或任何其他点?)
我最终需要改变
onSizeChanged
方法,如下所示:
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
path.reset()
val rect = RectF(0f, 0f, w.toFloat(), h.toFloat())
val inset = paint.strokeWidth
rect.inset(inset, inset)
// minimum is 1 because 0 does not close rectangle.
val radius = 1f
// Starting from the top-left corner, move in a counter-clockwise direction to create the desired path
path.moveTo(rect.left + radius, rect.top)
path.lineTo(rect.right - radius, rect.top)
path.arcTo(
RectF(rect.right - radius * 2, rect.top, rect.right, rect.top + radius * 2),
-90f,
90f
)
path.lineTo(rect.right, rect.bottom - radius)
path.arcTo(
RectF(
rect.right - radius * 2,
rect.bottom - radius * 2,
rect.right,
rect.bottom
),
0f,
90f
)
path.lineTo(rect.left + radius, rect.bottom)
path.arcTo(
RectF(rect.left, rect.bottom - radius * 2, rect.left + radius * 2, rect.bottom),
90f,
90f
)
path.lineTo(rect.left, rect.top + radius)
path.arcTo(
RectF(rect.left, rect.top, rect.left + radius * 2, rect.top + radius * 2),
180f,
90f
)
path.close()
length = PathMeasure(path, false).length
intervals[1] = length
intervals[0] = intervals[1]
val effect: PathEffect = DashPathEffect(intervals, length)
paint.setPathEffect(effect)
}