How to use drawRect to draw in a existing view?

女生的网名这么多〃 提交于 2019-12-01 11:11:51

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;
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!