In my Mac application, I am letting the user paint on a grid, each square on the grid representing a pixel and having its own colour. Is it possible to then take that colour and simple one by one produce an image by setting the pixel colour?
I can’t really think of how else to do this. I need to export an image once the user has painted into this grid that I am making.
Thanks.
The aim of my app:
The user can paint into a grid. So the final image might be 16×16 pixels in size, however the user in the app can paint each pixel into a square of a grid (16×16). This is then outputted into the format of the final image which might be 16×16 pixels, literally on screen. While the grid visually while painting is larger. Each square on the grid represents a pixel in the final image, and the user can put a single colour into each square. Hopefully this makes sense, if not I shall try and elaborate and link an example.
[TLDR: Use Model-View-Controller.]
There are three distinct things to consider here:
Keeping those elements separate in your mind and your implementation will make your life a lot easier.
#1 is a model, and in this case will likely consist of an array of 256 (or however many) colour values, probably along with some descriptive data like the pixel dimensions and colour space. For something this simple you might not want to create a separate model class (although you should), but even if it’s just an array ivar sitting in a monolithic app class you should still think of it as a distinct entity in its own right.
#2 is a view (with controller tendencies), and you should almost certainly implement it using a custom
NSViewsubclass. It would be possible to build a grid of 256 instances ofNSColorWellor some other existingNSViewtype, but that would just be silly. The view has two jobs:NSBezierPathare your friends here, especially the class methodsfillRectandstrokeRect.#3 is in some ways just another kind of view, in that it is another way of representing the model. Code for producing it is sometimes included with the model (say if there’s only one canonical way of serialising the data), but it’s good practice to put it somewhere else, especially if you might want to add other arbitrary mechanisms later.
The key here is that this image is really nothing to do with the
NSViewside of things, it’s a matter of taking the model data and writing it out. You can do the writing viaNSImagemethods or via Core Graphics, as mentioned in the other answers, but what you absolutely shouldn’t do is try to manhandle it directly off the screen. That way lies madness!