@@ -8,23 +8,28 @@ import cnames.structs.CGColorSpace
88import cnames.structs.CGImage
99import kotlinx.cinterop.CPointed
1010import kotlinx.cinterop.CPointer
11+ import kotlinx.cinterop.CValue
1112import kotlinx.cinterop.readBytes
1213import org.jetbrains.skia.ColorAlphaType
1314import org.jetbrains.skia.ColorType
1415import org.jetbrains.skia.Image
1516import org.jetbrains.skia.ImageInfo
1617import platform.CoreGraphics.CGBitmapContextCreate
1718import platform.CoreGraphics.CGColorSpaceCreateDeviceRGB
19+ import platform.CoreGraphics.CGContextClearRect
1820import platform.CoreGraphics.CGContextDrawImage
1921import platform.CoreGraphics.CGContextRef
2022import platform.CoreGraphics.CGContextRelease
23+ import platform.CoreGraphics.CGImageAlphaInfo
2124import platform.CoreGraphics.CGImageGetHeight
2225import platform.CoreGraphics.CGImageGetWidth
2326import platform.CoreGraphics.CGImageRef
27+ import platform.CoreGraphics.CGRect
2428import platform.CoreGraphics.CGRectMake
2529import platform.posix.free
2630import platform.posix.malloc
2731import platform.posix.size_t
32+ import platform.posix.uint32_t
2833
2934internal fun CGImageRef.toSkiaImage (): Image {
3035 val cgImage: CPointer <CGImage > = this
@@ -36,30 +41,34 @@ internal fun CGImageRef.toSkiaImage(): Image {
3641 val bytesPerPixel: ULong = bitsPerPixel / bitsPerComponent
3742 val bytesPerRow: ULong = width * bytesPerPixel
3843 val bufferSize: ULong = width * height * bytesPerPixel
44+ val bitmapInfo: uint32_t = CGImageAlphaInfo .kCGImageAlphaPremultipliedLast.value
45+
46+ check(bufferSize != 0UL ) { " image can't be 0 bytes" }
47+ check(width > 0UL ) { " width should be more then 0 px ($width )" }
48+ check(height > 0UL ) { " height should be more then 0 px ($height )" }
3949
4050 val data: CPointer <out CPointed > = malloc(bufferSize)
4151 ? : throw IllegalArgumentException (" can't allocate memory for render bitmap of $cgImage " )
4252
53+ val rect: CValue <CGRect > = CGRectMake (
54+ x = 0.0 ,
55+ y = 0.0 ,
56+ width = width.toDouble(),
57+ height = height.toDouble()
58+ )
59+
4360 val ctx: CGContextRef = CGBitmapContextCreate (
4461 data = data,
4562 width = width,
4663 height = height,
4764 bitsPerComponent = bitsPerComponent,
4865 bytesPerRow = bytesPerRow,
4966 space = space,
50- bitmapInfo = platform. CoreGraphics . CGImageAlphaInfo .kCGImageAlphaPremultipliedLast.value
67+ bitmapInfo = bitmapInfo
5168 ) ? : throw IllegalArgumentException (" can't create bitmap context for $cgImage " )
5269
53- CGContextDrawImage (
54- ctx,
55- rect = CGRectMake (
56- x = 0.0 ,
57- y = 0.0 ,
58- width = width.toDouble(),
59- height = height.toDouble()
60- ),
61- image = cgImage
62- )
70+ CGContextClearRect (c = ctx, rect = rect)
71+ CGContextDrawImage (c = ctx, rect = rect, image = cgImage)
6372
6473 CGContextRelease (ctx)
6574
0 commit comments