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

问题描述 投票:0回答:1

我正在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>               

android kotlin draw android-custom-view android-wrap-content
1个回答
0
投票

改变你的onMeasure。你将测量的宽度和高度设置为相同的值。如果您只想显示上半圈,则需要将高度设置为宽度的一半。否则,它会认为视图是高度的整圆。

© www.soinside.com 2019 - 2024. All rights reserved.