我实际上是在尝试在视图上画线。为了在每次绘制之前不清除上下文,我知道我必须创建自己的上下文才能绘制它。
我找到了这种创建上下文的方法:
CGContextRef MyCreateBitmapContext (int pixelsWide,
int pixelsHigh)
{
CGContextRef context = NULL;
CGColorSpaceRef colorSpace;
void * bitmapData;
int bitmapByteCount;
int bitmapBytesPerRow;
bitmapBytesPerRow = (pixelsWide * 4);
bitmapByteCount = (bitmapBytesPerRow * pixelsHigh);
colorSpace = CGColorSpaceCreateDeviceRGB();
bitmapData = calloc( bitmapByteCount, sizeof(int) );
if (bitmapData == NULL)
{
fprintf (stderr, "Memory not allocated!");
return NULL;
}
context = CGBitmapContextCreate (bitmapData,
pixelsWide,
pixelsHigh,
8, // bits per component
bitmapBytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast);
if (context== NULL)
{
free (bitmapData);
fprintf (stderr, "Context not created!");
return NULL;
}
CGColorSpaceRelease( colorSpace );
return context;
}
但我的问题是:我怎样才能使用这个上下文来避免每次都清理我的视图?
编辑 (在@Peter Hosey 的回答之后) :
我尝试做类似的事情:
- (void)drawRect:(CGRect)rect {
// Creation of the custom context
CGContextRef context = UIGraphicsGetCurrentContext();
CGImageRef cgImage = CGBitmapContextCreateImage(context);
CGContextDrawImage(context, CGRectMake(0, 0, self.frame.size.width, self.frame.size.height), cgImage);
CGImageRelease(cgImage);
if (isAuthorizeDrawing) {
[self drawInContext:context andRect:rect]; // Method which draw all the lines sent by the server
isAuthorizeDrawing = NO;
}
// Draw the line
[currentDrawing stroke];
}
我还将 UIView 的 clearsContextBeforeDrawing 设置为 NO。
当我缩放时(isAuthorizeDrawing 设置为 YES 以重绘所有正确缩放的线条),线条不会消失,但是当我尝试绘制新线条时(isAuthorizeDrawing 设置为 NO 以便在每次 setNeedsDisplay 调用时不重绘所有内容),所有的线条都消失了,绘图速度真的很慢..:/
难道我做错了什么 ?
编辑 2
这是我的绘图方法:
-(void)drawInContext:(CGContextRef)context {
for (int i = 0; i < self.drawings.count; ++i) {
Drawing* drawing = [self.drawings objectAtIndex:i];
CGContextSetStrokeColorWithColor(context, drawing.colorTrait.CGColor);
CGContextSetLineWidth(context, 1.0);
CGContextMoveToPoint(context, [[drawing.points objectAtIndex:0] CGPointValue].x * self.zoomScale, [[drawing.points objectAtIndex:] CGPointValue].y * self.zoomScale);
for (int i = 1; i < drawing.points.count; i++) {
CGContextAddLineToPoint(context, [[drawing.points objectAtIndex:i] CGPointValue].x * self.zoomScale, [[drawing.points objectAtIndex:i] CGPointValue].y * self.zoomScale);
}
CGContextStrokePath(context);
}
}
-(void)drawRect:(CGRect)rect {
if (isRedrawing) {
[self drawInContext:UIGraphicsGetCurrentContext()];
isRedrawing = NO;
}
[[UIColor redColor] set];
[currentPath stroke];
}