scoop:scoop.ui.component:0.1.0
src/layout/content_fit.scoop
Selected production source · src/layout/content_fit.scoop
1
package scoop.ui.component3
import scoop.graphics.*4
import scoop.ui.*6
public enum ContentFit {7
Contain, Cover, Fill, None8
}10
/** Fits logical content without applying a pixel density or mirroring its drawing. */11
public fun fitContent(12
naturalSize: Size,13
bounds: Rect,14
fit: ContentFit = ContentFit.Contain,15
alignment: Alignment = Alignment(),16
direction: LayoutDirection = LayoutDirection.Ltr17
): Rect {18
checkContentSize(naturalSize)19
requireComponent(20
bounds.x.isFinite() &&21
bounds.y.isFinite() &&22
bounds.width.isFinite() &&23
bounds.height.isFinite() &&24
bounds.width >=25
0.0 &&26
bounds.height >=27
0.0 &&28
(bounds.x + bounds.width).isFinite() &&29
(bounds.y + bounds.height).isFinite(),30
"invalid content bounds"31
)32
if (bounds.width == 0.0 || bounds.height == 0.0)33
return Rect(bounds.x, bounds.y, 0.0, 0.0)34
val x = bounds.width / naturalSize.width35
val y = bounds.height / naturalSize.height36
val size =37
when (fit) {38
case Fill -> bounds.size39
case None -> naturalSize40
case Contain -> {41
val scale = upperBound(x, y)42
Size(naturalSize.width * scale, naturalSize.height * scale)43
}44
case Cover -> {45
val scale = lowerBound(x, y)46
Size(naturalSize.width * scale, naturalSize.height * scale)47
}48
}49
checkContentSize(size)50
val origin = alignedOrigin(bounds, size, alignment, direction)51
requireComponent(origin.x.isFinite() && origin.y.isFinite(), "content fit overflow")52
return Rect(origin.x, origin.y, size.width, size.height)53
}55
internal fun checkContentSize(size: Size) {56
requireComponent(57
size.width.isFinite() && size.height.isFinite() && size.width > 0.0 && size.height > 0.0,58
"content natural size must be positive and finite"59
)60
}62
internal fun measureContent(naturalSize: Size, constraints: Constraints): LayoutMetrics {63
checkContentSize(naturalSize)64
var scale = 1.065
when (constraints.maxWidth) {66
case Some(val width) -> scale = upperBound(scale, width / naturalSize.width)67
case None -> {}68
}69
when (constraints.maxHeight) {70
case Some(val height) -> scale = upperBound(scale, height / naturalSize.height)71
case None -> {}72
}73
return LayoutMetrics(74
constraints.constrain(Size(naturalSize.width * scale, naturalSize.height * scale))75
)76
}