【发布时间】:2012-07-09 12:16:04
【问题描述】:
我正在使用 CgLayer 上的 unod 重做操作,我尝试了一些代码,但无法使其正常工作,不知道我哪里出错了,下面是我编写的代码
这是我的 drawRect 函数
- (void)drawRect:(CGRect)rect
{
m_backgroundImage = [UIImage imageNamed:@"bridge.jpg"];
CGPoint drawingTargetPoint = CGPointMake(0,0);
[m_backgroundImage drawAtPoint:drawingTargetPoint];
switch(drawStep)
{
case DRAW:
{
CGContextRef context = UIGraphicsGetCurrentContext();
if(myLayerRef == nil)
{
myLayerRef = CGLayerCreateWithContext(context, self.bounds.size, NULL);
}
CGContextDrawLayerAtPoint(context, CGPointZero, myLayerRef);
break;
}
case UNDO:
{
[curImage drawInRect:self.bounds];
break;
}
default:
break;
}
}
在触摸结束时,我将图层转换为 NSValue 并作为 keyValue 对存储到 NSDictionary 中,然后将字典对象添加到数组中。
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
NSValue *layerCopy = [NSValue valueWithPointer:myLayerRef];
NSDictionary *lineInfo = [NSDictionary dictionaryWithObjectsAndKeys:layerCopy, @"IMAGE",
nil];
[m_pathArray addObject:lineInfo];
NSLog(@"%i",[m_pathArray count]);
}
下面是我的撤消功能
- (void)undoButtonClicked
{
if([m_pathArray count]>0)
{
NSMutableArray *_line=[m_pathArray lastObject];
[m_bufferArray addObject:[_line copy]];
[m_pathArray removeLastObject];
drawStep = UNDO;
[self redrawLine];
}
}
//Redraw functions
- (void)redrawLine
{
NSDictionary *lineInfo = [m_pathArray lastObject];
NSValue *val = [lineInfo valueForKey:@"IMAGE"];
CGLayerRef layerToShow = (CGLayerRef) [val pointerValue];
CGContextRef context1 = CGLayerGetContext(layerToShow);
CGContextDrawLayerAtPoint(context1, CGPointMake(00, 00),layerToShow);
[self setNeedsDisplayInRect:self.bounds];
}
我认为这是我出错的地方。所以请朋友们帮帮我。
从下面的 cmets 中,我添加了函数,它在 Cglayer 中绘制(这个函数我正在调用 touchesMovedEvent。
- (void) drawingOperations
{
CGContextRef context1 = CGLayerGetContext(myLayerRef);
CGPoint mid1 = midPoint(m_previousPoint1, m_previousPoint2);
CGPoint mid2 = midPoint(m_currentPoint, m_previousPoint1);
CGContextMoveToPoint(context1, mid1.x, mid1.y);
CGContextAddQuadCurveToPoint(context1, m_previousPoint1.x, m_previousPoint1.y, mid2.x, mid2.y);
CGContextSetLineCap(context1, kCGLineCapRound);
CGContextSetLineWidth(context1, self.lineWidth);
CGContextSetStrokeColorWithColor(context1, self.lineColor.CGColor);
CGContextSetAllowsAntialiasing(context1, YES);
CGContextSetInterpolationQuality(context1, kCGInterpolationHigh);
CGContextSetAlpha(context1, self.lineAlpha);
CGContextStrokePath(context1);
}
问候 兰吉特
【问题讨论】:
-
你没有在图层的上下文中绘制任何东西。
redrawLine中的代码是您展示的唯一代码,它甚至可以获取图层的上下文,但它所做的只是尝试将图层绘制到自身中。那么,除了缺少任何绘图之外,您所说的这段代码不起作用是什么意思? -
您好彼得,感谢您的回复。不绘制到图层的上下文中,您的意思是进入 redrawLine 函数或 Case: DRAW?。我认为您与 redrawLine 函数有关,因为在 Case:DRAW 中,我正在绘制图层的上下文。第二件事,我是否应该为撤消重做功能或其他东西存储层,我的“touchesEnded”功能是否正确?因为我尝试使用 NSLog 对其进行调试,并且每次 CgLayer 的 NSValue 都是相同的。所以我把他们弄糊涂了。
-
不,
drawRect:不会绘制到图层的上下文中。drawRect:中的DRAW案例将图层绘制到 UIKit 的当前上下文中 - 即到屏幕上。redrawLine中的代码确实绘制到层的上下文中,但它也将层绘制到该上下文中——正如我所说,将层绘制到自身中。 -
谢谢你的回复,那请告诉我应该怎么做?
-
好了,现在你有了一个绘制到图层中的方法,但是你在什么时候调用它呢?您显示的代码都没有。
标签: ios cocoa-touch quartz-graphics quartz-2d cglayer