1 /*
2  * Copyright 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package androidx.compose.ui.text.android.style
17 
18 import android.graphics.Paint.FontMetricsInt
19 import kotlin.math.ceil
20 
21 /**
22  * The span which modifies the height of the covered paragraphs. A paragraph is defined as a segment
23  * of string divided by '\n' character. To make sure the span work as expected, the boundary of this
24  * span should align with paragraph boundary.
25  *
26  * @param lineHeight The specified line height in pixel unit, which is the space between the
27  *   baseline of adjacent lines.
28  * @constructor Create a LineHeightSpan which sets the line height to `height` physical pixels.
29  */
30 internal class LineHeightSpan(val lineHeight: Float) : android.text.style.LineHeightSpan {
31 
chooseHeightnull32     override fun chooseHeight(
33         text: CharSequence,
34         start: Int,
35         end: Int,
36         spanstartVertical: Int,
37         lineHeight: Int,
38         fontMetricsInt: FontMetricsInt
39     ) {
40         // In StaticLayout, line height is computed with descent - ascent
41         val currentHeight = fontMetricsInt.lineHeight()
42         // If current height is not positive, do nothing.
43         if (currentHeight <= 0) {
44             return
45         }
46         val ceiledLineHeight = ceil(this.lineHeight).toInt()
47         val ratio = ceiledLineHeight * 1.0f / currentHeight
48         fontMetricsInt.descent = ceil(fontMetricsInt.descent * ratio.toDouble()).toInt()
49         fontMetricsInt.ascent = fontMetricsInt.descent - ceiledLineHeight
50     }
51 }
52