Hi guys, I am implementing a map in my application...
# ios
e
Hi guys, I am implementing a map in my application with markers, which are SVG images, and I am having a performance problem. Most of the markers need to be shown in black and white, not colored. I have around 300 markers, where 280 more or less are like that. The problem is that in the first execution of the screen, the iPhone uses around 250 MB memory, it creates the markers, resize them and make them black and white. If I leave the screen and come back to it a couple of times, the memory usage raises to 2GB and the app crahses. If I don't make them black and white it does not happen and the memory stays in 250-300 mb. Is there any optimized way to fix this problem? A different way to make images black and white or release non used resources when I leave the screen? I explain more details of the implementation in the thread.
The resize function:
Copy code
fun UIImage.resizeImage(targetSize: CValue<CGSize>): UIImage? {
    val image = this
fun UIImage.resizeImage(
    targetSize: CValue<CGSize>,
    alpha: Double = 1.0,
): UIImage? {
    targetSize.useContents {
        UIGraphicsBeginImageContextWithOptions(targetSize, false, 0.0)
        image.drawInRect(CGRectMake(0.0, 0.0, this.width, this.height))
        this@resizeImage.drawInRect(
            rect = CGRectMake(0.0, 0.0, this.width, this.height),
            blendMode = CGBlendMode.kCGBlendModeNormal,
            alpha = alpha,
        )
        val resizedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return resizedImage
    }
}
The black and white function:
Copy code
@OptIn(ExperimentalForeignApi::class)
fun UIImage.toBlackAndWhite(): UIImage? {
    val width = size.useContents { width.toInt() }
    val height = size.useContents { height.toInt() }
    val colorSpace = CGColorSpaceCreateDeviceGray()

    val context =
        CGBitmapContextCreate(
            data = null,
            width = width.toULong(),
            height = height.toULong(),
            bitsPerComponent = 8u,
            bytesPerRow = 0u,
            space = colorSpace,
            bitmapInfo = CGImageAlphaInfo.kCGImageAlphaPremultipliedLast.value,
        ) ?: return null

    val cgImage = this.CGImage ?: return null
    CGContextTranslateCTM(context, 0.0, height.toDouble())
    CGContextScaleCTM(context, 1.0, -1.0)

    CGContextDrawImage(context, CGRectMake(0.0, 0.0, width.toDouble(), height.toDouble()), cgImage)

    val grayCGImage = CGBitmapContextCreateImage(context) ?: return null

    return UIImage(grayCGImage)
}
f
My guess to do the same thing directly in swift from an iOS App and see the difference of memory usage.