Mac OS Cocoa: Draw a simple pixel on a canvas

后端 未结 8 657
悲哀的现实
悲哀的现实 2021-02-02 01:21

I wish I would find an answer for this. I have searched and searched and couldn\'t the right answer. Here is my situation:

In a Mac OS Cocoa Application, I want to draw

8条回答
  •  情话喂你
    2021-02-02 01:27

    Cocoa's low-level drawing API is Core Graphics (Quartz). You obtain a drawing context and issue commands to draw onto that context. The API is designed to be device-independent (you use the same commands to draw onto the screen as you would to draw onto paper, when printing). Therefore, there are no commands for filling in individual pixels, because there's no such thing as a pixel on paper. Even on the screen, your view may have been transformed in some way so that a single point doesn't map to a single device pixel.

    If you want to draw a single pixel, you need to specify a rectangle that is the size of a single pixel, then fill it in. For the pixel at (x,y), you would want a rectangle with origin of (x-0.5,y-0.5) and a size of (1,1).

    You can do that with NSBezierPath, or you can get a Core Graphics context (CGContextRef) from [[NSGraphicsContext currentContext] graphicsPort] and use functions like CGContextFillRect().

    This obviously won't be very fast if you are drawing a lot of pixels; that's not what the API is designed for. If that's what you need to do, consider creating a buffer with malloc and writing your pixel data to that, then using Core Graphics to convert it into a CGImageRef, which can be drawn to the screen.

提交回复
热议问题