How to use drawRect to draw in a existing view?

后端 未结 2 1384
梦毁少年i
梦毁少年i 2021-01-15 02:49

I\'m doing a GPS tracking app. Every time it receives a Latitude/Longitude it converts it to (x,y) coordinates and calls drawRect to draw a line between two (x,

相关标签:
2条回答
  • 2021-01-15 03:24

    What exactly to you mean by "old contents"? If you want to draw a line from your GPS data, you have to draw all points every time in the implementation of drawRect.

    0 讨论(0)
  • 2021-01-15 03:36

    UIView does not have a canvas model. If you want to keep a canvas, you should create a CGLayer or a CGBitmapContext and draw onto that. Then draw that in your view.

    I would create an ivar for a CGLayerRef, and then drawRect: would look something like this (untested):

    - (void)drawRect:(CGRect)rect {
        if (self.cgLayer == NULL) {
            CGLayerRef layer = CGLayerCreateWithContext(UIGraphicsContextGetCurrent(), self.bounds, NULL);
            self.cgLayer = layer;
            CGLayerRelease(layer);
        }
    
        ... various Core Graphics calls with self.cgLayer as the context ...
    
        CGContextDrawLayerInRect(UIGraphicsContextGetCurrent(), self.bounds, self.cgLayer);
    }
    

    Whenever you wanted to clear your canvas, just self.cgLayer = NULL.

    setCgLayer: would be something like this:

    - (void)setCgLayer:(CGLayerRef)aLayer {
        CGLayerRetain(aLayer);
        CGLayerRelease(cgLayer_);
        cgLayer_ = aLayer;
    }
    
    0 讨论(0)
提交回复
热议问题