1
votes

I have an image view defined as:

@IBOutlet weak var imgView: NSImageView!

Image data which gets written into defined as:

var imageData = [[Int?]](
    repeating: [Int?](repeating: nil, count: 256),
    count: 240
)

I'm invoking my onDraw method from a timer. The core part of the drawing which takes the longest is:

    let image = NSImage(size: NSSize(width: 240, height: 256))

    image.lockFocus()

    for y in 0..<240 {
        for x in 0..<256 {
            let n = imageData[y][x]
            let scaledY = 255 - y
            let c = NSColor(red: CGFloat(((n! & 0xFF000000) >> 24)) / 255.0, green: CGFloat((n! & 0x00FF0000) >> 16) / 255.0, blue: CGFloat((n! & 0x0000FF00) >> 8) / 255.0, alpha: 1.0)
            c.drawSwatch(in: NSRect(x: x, y: scaledY, width: 1, height: 1))
        }
    }

    image.unlockFocus()

    imgView.image = image

I've tried changing my timer speed but it looks like the drawing part is taking too long. Trying to reach 30 FPS but it ends up skipping frames due to the time it takes to draw the image data.

Commenting out the creation of the NSColor object and the c.drawSwatch it runs perfectly fast. But obviously draws nothing.

So is there a faster way to draw into an NSImage? Sorry I'm fairly new to Swift and Cocoa development.

1
Is there anything specific you are trying to draw?P_O
Why are you having to redraw this every frame?Mobile Ben
I don't even know what the drawSwatch guy is. Your timer? What timer? Where?El Tomato

1 Answers

2
votes

It's hard to tell exactly what you're trying to do from your question.

My guess is that you should create a CGImage from a data provider with the proper bitmap metadata and then create an NSImage from that. If you want scaling, don't attempt to do it when creating the CGImage. Just give it the raw image data as directly as possible. Later, when creating the NSImage from it specify a size.

In any case, avoid recreating these image objects unless and until the underlying image data has changed. For example, don't recreate the image every time your view is asked to draw itself.