Search code examples
objective-cmacosdrawingcalayerpaint

Drawing line on a CALayer in OSx


I would like to know if you can help me with painting on layers.

The situation is this

I am programming on this kind of screen http://multitouch.com, 12 touches simultaneously. In the app I am developing, I can manage multiple images. I can rotate, scale an move at the same time all images (maximum 12 touches on the screen!) To accomplish this I use ONLY layers for performances. Every image is represented by a CALayer, then I create my CALayer's and set the image as its 'contents'. The hierarchy is this.

I have only a NSView.

  • NSView "Container_View"
  • CALayer "Images_Layer" as sublayer of the "Container_View" layer (they have the same frame)
  • CALayer "Img_1_Layer", CALayer "Img_2_Layer", CALayer "Img_3_Layer", etc as sublayer of "Images_Layer"

As I told you before, I can rotate, scale and move my Images.

Double tap on a single image, I lock the whole screen, I can still rotate and move the image but ONLY with 2 fingers.

Now I would like that user can draw with 1 finger on this image.

The main problem is that I have not experience with graphics and all example on internet are about draw line on view.

The question is How to draw with a finger on a CALayer. I have only CALayer, I cannot have NSView

Many thantk in advance, Sergio


Hi Mazyod, the CALayer class that provides the Image is very big.

Please try to understand this context

MainWindow as root naturally

NSViewController called MainViewController with a custom NSView as root view - this view is called Container and it's set as contentView of the MainWindow

CALayer called Images_Layer - it's a layer added as SubLayer of the Container's layer

CALayer called Img_Layer - it's a layer added as SubLayer of the Images_Layer (I have one of this for each image, set as contents naturally, then an CGImageRef)

When I click on an Image (ImgLayer), 3 methods are fired as usual:

onTouchPointDown - with x, y etc onTouchPointMove - with x, y etc onTouchPointUp - with x, y etc


Solution

  • Ok, I have found.

    • set the layer's delegate
    • override this method in the delegate
    • call layer setNeedDisplay method when you need

    - (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx

    {

    NSGraphicsContext *gc = [NSGraphicsContext graphicsContextWithGraphicsPort:ctx flipped:NO];
    [NSGraphicsContext saveGraphicsState];
    
    [NSGraphicsContext setCurrentContext:gc];
    
    // draw points with bezier path
    
    [NSGraphicsContext restoreGraphicsState];
    

    }