Skip to content

Conversation

@Werechess
Copy link

Screen_recording_20251029_221729.webm

.mapIndexed { index, entry ->
val percentage = entry.value / totalAmount
val sweepAngle = percentage * 360f
currentAngle += sweepAngle

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Привет! Вы увеличиваете currentAngle до того, как вычисляется startAngle, из-за этого секторы будут перекрываться или располагаться неправильно. Нужно сначала сохранить текущий угол в startAngle, а потом увеличивать currentAngle

amount = entry.value,
percentage = percentage * 100, // Human-readable
color = CategoryColor.entries[index % CategoryColor.entries.size].colorCode,
startAngle = currentAngle - sweepAngle,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Здесь сохраненный startAngle

}.toMutableList()
}

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

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Обращаю внимание на ТЗ: "Обязательно реализуйте метод onMeasure и учтите все возможные MeasureSpecs". Сейчас высота обрабатывается через resolveSize, что не учитывает все режимы MeasureSpec. Для кругового графика лучше явно обработать все три режима (EXACTLY, AT_MOST, UNSPECIFIED) и выбрать минимальный размер для сохранения квадратной формы.


if (distance > radius) return null

var angle = Math.toDegrees(atan2(dy.toDouble(), dx.toDouble())).toFloat()

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Используется java.lang.Math, хотя уже импортирован kotlin.math.atan2. Для консистентности лучше использовать kotlin.math.toDegrees

var angle = toDegrees(atan2(dy.toDouble(), dx.toDouble())).toFloat()

private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.BLACK
textAlign = Paint.Align.CENTER
textSize = 80f

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Размер текста жестко задан и не масштабируется с размером View. Рекомендую вычислять его в onSizeChanged в зависимости от радиуса, например: textPaint.textSize = radius * 0.1f

val groupedTransactions = transactions.groupBy { it.category }
.mapValues { entry -> entry.value.sumOf { transaction -> transaction.amount } }

val totalAmount = groupedTransactions.values.sum().toFloat()

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Можно еще добавить проверку на totalAmount <= 0f перед делением, чтобы избежать некорректных углов при пустых данных

val json = resources.openRawResource(R.raw.payload)
.bufferedReader().use { it.readText() }
val type = object : TypeToken<List<Transaction>>() {}.type
return Gson().fromJson(json, type)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Создается новый экземпляр Gson при каждом вызове. Gson потокобезопасен и может быть переиспользован. Если вынести в companion object, будет красиво

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants