如何在半圈自定义视图上包装内容?

时间:2019-04-02 18:16:07

标签: android kotlin draw android-custom-view android-wrap-content

我正在Android上制作半圈自定义视图。但是,我正在努力删除包装内容上不需要的底部空白。我认为是因为它是基于“完整的圆”计算得出的。 我将分享我的自定义视图实现以及如何从应用程序中调用它。 另请参见以下图片: Click here for the screenshot

注意:如果更改onMeasure大小,则它将切去上方的圆圈: Click here for the screenshot

class CircularProgressView(context: Context, attrs: AttributeSet) : View(context, attrs) {

    private var circle = RectF()
    private val paint = Paint()
    private var size = 0

    init {
        paint.isAntiAlias = true
        paint.style = Paint.Style.STROKE
        paint.strokeWidth = strokeWidth.toFloat()
        paint.strokeCap = Paint.Cap.BUTT

        setupAttributes(attrs)
    }

    private fun setupAttributes(attrs: AttributeSet?) {

        // TypedArray objects are shared and must be recycled.
        typedArray.recycle()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        drawBackground(canvas)
    }


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        size = Math.min(measuredWidth, measuredHeight)

        setMeasuredDimension(size, size)
    }


    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)

        val centerX = w / 2
        val centerY = h / 2

        // Pick the minimum value so that it can fit the container. Radius is half size
        val radius = size / 2f

        // Create the background and progress circle, adding dialStrokeWidth in equation so that make sure the dial can fit container
        circle.top = (centerY - radius)
        circle.bottom = (centerY + radius)
        circle.left = (centerX - radius)
        circle.right = (centerX + radius)
    }

    private fun drawBackground(canvas: Canvas) {
        paint.shader = null
        paint.color = backGroundColor
        canvas.drawArc(circle, startAngle, sweepAngle, false, paint)
    }
}

这是我的用法:

<com.enova.circular_progress.CircularProgressView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:background="@color/white"
                    app:backgroundColor="@color/colorHint"
                    app:dialColor="@color/colorPrimary"
                    app:foregroundColorEnd="@color/colorPrimary"
                    app:foregroundColorStart="@color/colorPrimaryDark"
                    app:layout_constraintLeft_toLeftOf="parent"
                    app:layout_constraintRight_toRightOf="parent"
                    app:layout_constraintTop_toTopOf="parent"
                    app:percent="80">
                </com.enova.circular_progress.CircularProgressView>               

1 个答案:

答案 0 :(得分:0)

更改onMeasure。您正在将测量的宽度和高度设置为相同的值。如果只想显示顶部的半个圆,则要将高度设置为宽度的一半。否则,它将认为视图是整个高度的圆。