微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

iPhone-试图在CALayer上画线

如何解决iPhone-试图在CALayer上画线

| 我有一个用于使用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”,您将可以使用该视图。但是不要那样做,做我上面显示的。在大多数情况下,您不必考虑图层。     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。