要在自定义的ProgressBar圆形加载中间画一张图片,可以按照以下步骤进行:

  1. 首先,创建一个自定义的ProgressBar类,继承自ProgressBar类,重写onDraw方法。
class CustomProgressBar @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : ProgressBar(context, attrs, defStyleAttr) {

    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val bitmap: Bitmap

    init {
        // 加载图片资源
        bitmap = BitmapFactory.decodeResource(resources, R.drawable.your_image)
    }

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

        // 获取进度值
        val progress = progress.toFloat() / max

        // 计算圆形加载的角度
        val sweepAngle = progress * 360

        // 获取ProgressBar的宽度和高度
        val width = width.toFloat()
        val height = height.toFloat()

        // 计算圆形加载的半径
        val radius = min(width, height) / 2

        // 计算圆形加载的圆心坐标
        val centerX = width / 2
        val centerY = height / 2

        // 绘制圆形加载的背景圆环
        paint.color = Color.GRAY
        paint.strokeWidth = 10f
        paint.style = Paint.Style.STROKE
        canvas.drawCircle(centerX, centerY, radius, paint)

        // 绘制圆形加载的进度圆弧
        paint.color = Color.BLUE
        paint.strokeWidth = 10f
        paint.style = Paint.Style.STROKE
        canvas.drawArc(
            centerX - radius,
            centerY - radius,
            centerX + radius,
            centerY + radius,
            -90f,
            sweepAngle,
            false,
            paint
        )

        // 计算图片的左上角坐标
        val left = centerX - radius + 10
        val top = centerY - radius + 10

        // 绘制图片
        canvas.drawBitmap(bitmap, left, top, paint)
    }
}
  1. 在布局文件中使用自定义的ProgressBar。
<com.example.yourapp.CustomProgressBar
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true" />

这样,就可以在自定义的ProgressBar圆形加载中间画一张图片了

Android Kotlin 自定义ProgressBar圆形加载 中间画一张图片

原文地址: http://www.cveoy.top/t/topic/i1Ro 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录