问题描述
|
我有一个用于使用CALayer的UIView类。该层将用于基于触摸绘制线条。
这是定义类的方式:
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self == nil) {
return nil;
}
self.layer.backgroundColor = [UIColor redColor].CGColor;
self.userInteractionEnabled = YES;
path = CGPathCreateMutable();
return self;
}
那么我在touchesBegan,touchesMoved和touchesEnded上有以下几行...
**touchesBegan**
CGPathMovetoPoint(path,NULL,currentPoint.x,currentPoint.y);
[self.layer setNeedsdisplay];
**touchesMoved**
CGPathAddLinetoPoint(path,currentPoint.y);
[self.layer setNeedsdisplay];
**touchesEnded**
CGPathAddLinetoPoint(path,currentPoint.y);
[self.layer setNeedsdisplay];
那我有这个
-(void)drawInContext:(CGContextRef)context {
CGContextSetstrokeColorWithColor(context,[[UIColor greenColor] CGColor]);
CGContextSetlinewidth(context,3.0);
CGContextBeginPath(context);
CGContextAddpath(context,path);
CGContextstrokePath(context);
}
调用了touchesBegan / Moved / Ended方法,但从未调用过drawInContext方法...
我想念什么???
谢谢。
解决方法
当您可以轻松使用UIKit api时,您正在混合图层和视图并使用CG api。
在您的init方法中执行此操作;
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self == nil) {
return nil;
}
self.backgroundColor = [UIColor redColor];
// YES is the default for UIView,only UIImageView defaults to NO
//self.userInteractionEnabled = YES;
[self setPath:[UIBezierPath bezierPath]];
[[self path] setLineWidth:3.0];
return self;
}
在您的事件处理代码中;
**touchesBegan**
[[self path] moveToPoint:currentPoint];
[self setNeedsDisplay];
**touchesMoved**
[[self path] addLineToPoint:currentPoint];
[self setNeedsDisplay];
**touchesEnded**
[[self path] addLineToPoint:currentPoint];
[self setNeedsDisplay];
然后像这样实现implement5ѭ;
- (void)drawRect:(CGRect)rect {
[[UIColor greenColor] setStroke];
[[self path] stroke];
}
我是从内存中键入此内容的,因此它可能无法编译,可能会重新格式化您的硬盘驱动器或从火星召唤入侵者入侵您的房屋。好吧,也许不是...
该视图是图层的委托,因此,如果您将绘图方法命名为“ 7”,您将可以使用该视图。但是不要那样做,做我上面显示的。在大多数情况下,您不必考虑图层。