iOS 开发 学习iOS语法技巧iOS Developer

UITouch绘图,不使用贝塞尔曲线

2016-02-16  本文已影响387人  芝麻绿豆

首先简单介绍一下UITouch吧!

属相与方法:

typedef NS_ENUM(NSInteger, UITouchPhase) {
    UITouchPhaseBegan,  (开始)           // whenever a finger touches the surface.
    UITouchPhaseMoved,  (移动)           // whenever a finger moves on the surface.
    UITouchPhaseStationary,  (无移动)      // whenever a finger is touching the surface but hasn't moved since the previous event.
    UITouchPhaseEnded,     (结束)      // whenever a finger leaves the surface.
    UITouchPhaseCancelled, (取消)      // whenever a touch doesn't end but we need to stop tracking (e.g. putting device to face)
};

如何绘图:

    UITouch *touch = [touches anyObject];
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, nil, [touch locationInView:self].x, [touch locationInView:self].y);
    [self.totalPathPoints addObject:(__bridge_transfer id)path];

可以不使用CGMutablePathRef,可以用数组然后再将self.totalPathPoints这个数组存在一个一个的小数组;然后遍历也可以,方法有很多种;

__bridge_transfer 让非Objective-C对象转换为Objective-C对象
 -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    [self drawLineWithTouches:touches];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [self drawLineWithTouches:touches];
}
-(void)drawLineWithTouches:(NSSet *)touches {
    UITouch *touch = [touches anyObject];
    CGMutablePathRef path = (__bridge_retained CGMutablePathRef)self.totalPathPoints.lastObject;
    CGPathAddLineToPoint(path, nil, [touch locationInView:self].x, [touch locationInView:self].y);
    [self setNeedsDisplay];
}
注意:用[self setNeedsDisplay]调用- (void)drawRect:(CGRect)rect才有效;不可以手动直接调用。
-(void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    for (id path in self.totalPathPoints) {
        CGMutablePathRef ref = (__bridge_retained CGMutablePathRef)path;
        CGContextAddPath(context, ref);
    }
    // 线段的宽度
    CGContextSetLineWidth(context, 5);
    [[UIColor blackColor] setStroke];
    CGContextSetLineCap(context, kCGLineCapRound);
    CGContextSetLineJoin(context, kCGLineJoinRound);
    CGContextStrokePath(context);
}
__bridge_retained 是将Objective-C对象转换为非Objective-C对象;Objective-C 和 Core Foundation 对象之间可以轻松的转换
效果图
上一篇 下一篇

猜你喜欢

热点阅读