ImageBitmapExt.kt 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package org.mjdev.desktop.extensions
  2. import androidx.compose.ui.graphics.Canvas
  3. import androidx.compose.ui.graphics.Color
  4. import androidx.compose.ui.graphics.ImageBitmap
  5. import androidx.compose.ui.graphics.Paint
  6. import org.mjdev.desktop.context.IDesktopContext
  7. import org.mjdev.desktop.data.DecodedImage
  8. import org.mjdev.desktop.helpers.decodeImage
  9. @Suppress("EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING")
  10. expect object ImageBitmapExt {
  11. suspend fun IDesktopContext.loadPicture(
  12. src: Any?
  13. ): ImageBitmap?
  14. }
  15. fun ByteArray.decodeImage(): DecodedImage? = decodeImage(this)
  16. var ImageBitmap.pixels: IntArray
  17. get() = IntArray(width * height).also { pixels -> readPixels(pixels) }
  18. set(value) = writePixels(value, 0, 0, width, height)
  19. fun ImageBitmap.fillRect(
  20. x: Int,
  21. y: Int,
  22. width: Int,
  23. height: Int,
  24. c: Color
  25. ) {
  26. Canvas(this).drawRect(
  27. x.toFloat(),
  28. y.toFloat(),
  29. width.toFloat(),
  30. height.toFloat(),
  31. Paint().apply { color = c }
  32. )
  33. }
  34. fun ImageBitmap.writePixels(
  35. data: IntArray,
  36. x: Int,
  37. y: Int,
  38. width: Int,
  39. height: Int
  40. ) {
  41. val paint = Paint()
  42. val canvas = Canvas(this)
  43. var index = 0
  44. for (j in 0 until height) {
  45. for (i in 0 until width) {
  46. val colorInt = data[index++]
  47. paint.color = Color(colorInt)
  48. canvas.drawRect(
  49. (x + i).toFloat(),
  50. (y + j).toFloat(),
  51. (x + i + 1).toFloat(),
  52. (y + j + 1).toFloat(),
  53. paint
  54. )
  55. }
  56. }
  57. }
  58. fun ImageBitmap.cut(
  59. x: Int,
  60. y: Int,
  61. width: Int,
  62. height: Int
  63. ): ImageBitmap {
  64. val srcPixels = this.pixels
  65. val result = ImageBitmap(width, height)
  66. val subPixels = IntArray(width * height)
  67. for (j in 0 until height) {
  68. for (i in 0 until width) {
  69. val srcIndex = (y + j) * this.width + (x + i)
  70. val dstIndex = j * width + i
  71. subPixels[dstIndex] = srcPixels.getOrElse(srcIndex) { 0 }
  72. }
  73. }
  74. result.pixels = subPixels
  75. return result
  76. }