BorderCropTransformation.skiko.kt
composeApp/src/skikoMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/BorderCropTransformation.skiko.kt
1package eu.friedcutlet.yokan.ui.screens.reader23import coil3.Bitmap4import coil3.size.Size5import coil3.transform.Transformation6import org.jetbrains.skia.Canvas7import org.jetbrains.skia.IRect8import org.jetbrains.skia.Image9import org.jetbrains.skia.ImageInfo1011internal actual fun createBorderCropTransformation(): Transformation = SkiaBorderCropTransformation1213private object SkiaBorderCropTransformation : Transformation() {14 override val cacheKey: String = "yokan-border-crop-v1"1516 override suspend fun transform(input: Bitmap, size: Size): Bitmap {17 val bounds = detectBorderCropBounds(input.width, input.height, input::getColor) ?: return input18 return input.subset(IRect.makeLTRB(bounds.left, bounds.top, bounds.rightExclusive, bounds.bottomExclusive))19 }20}2122internal actual fun createPageHalfTransformation(left: Boolean): Transformation = SkiaPageHalfTransformation(left)2324private class SkiaPageHalfTransformation(private val left: Boolean) : Transformation() {25 override val cacheKey: String = "yokan-page-half-${if (left) "left" else "right"}-v1"2627 override suspend fun transform(input: Bitmap, size: Size): Bitmap {28 val half = input.width / 229 if (half == 0) return input30 return input.subset(if (left) IRect.makeLTRB(0, 0, half, input.height) else IRect.makeLTRB(half, 0, input.width, input.height))31 }32}3334internal actual fun createWidePageRotation(degrees: Int): Transformation = SkiaWidePageRotation(degrees)3536private class SkiaWidePageRotation(private val degrees: Int) : Transformation() {37 override val cacheKey: String = "yokan-rotate-wide-$degrees-v1"3839 override suspend fun transform(input: Bitmap, size: Size): Bitmap {40 if (input.width <= input.height) return input41 val output = Bitmap()42 check(output.allocPixels(ImageInfo(input.imageInfo.colorInfo, input.height, input.width))) { "Unable to allocate rotated page" }43 val image = Image.makeFromBitmap(input)44 val canvas = Canvas(output)45 try {46 // Clockwise: (x, y) -> (height - y, x); counter-clockwise: (x, y) -> (y, width - x).47 if (degrees > 0) canvas.translate(input.height.toFloat(), 0f) else canvas.translate(0f, input.width.toFloat())48 canvas.rotate(degrees.toFloat())49 canvas.drawImage(image, 0f, 0f)50 } finally {51 canvas.close()52 image.close()53 }54 return output55 }56}5758private fun Bitmap.subset(bounds: IRect): Bitmap = Bitmap().also { result ->59 check(extractSubset(result, bounds)) { "Unable to crop image to $bounds" }60}61